[racket] The function that returns closure and symbols leaking

From: Neil Van Dyke (neil at neilvandyke.org)
Date: Sat May 14 23:11:50 EDT 2011

Kazimir Majorinc wrote at 05/14/2011 10:55 PM:
> How would you do that "idiomatically"?

One way is to use syntax extension.  Below, I have simplified your 
syntax for "counted" a little, although I could have also done your 
exact syntax by adding it to the "(_ VAR EXPR)" form.

;;;; BEGIN
#lang racket/base

(define-syntax counted
  (syntax-rules ()
    ((_ VAR EXPR)
     (let ((i 0))
       (lambda (VAR)
         (set! i (+ 1 i))
         (display i)
         (newline)
         EXPR)))))
       
(define f (counted x (+ x x)))

(f 3)
(f 9)
(f 27)
;;;; END

An arguably more idiomatic way to do this particular thing is to not use 
syntax extension, but first-class closures:

;;;; BEGIN
#lang racket/base

(define (make-counted proc)
 (let ((i 0))
   (lambda (val)
     (set! i (+ 1 i))
     (display i)
     (newline)
     (proc val))))

(define f (make-counted (lambda (x) (+ x x))))

(f 3)
(f 9)
(f 27)
;;;; END

The name "make-counted" is convention, but you could also name it "counted".

-- 
http://www.neilvandyke.org/


Posted on the users mailing list.