[racket] The function that returns closure and symbols leaking

From: Ryan Culpepper (ryanc at ccs.neu.edu)
Date: Sat May 14 23:10:02 EDT 2011

On 05/14/2011 08:55 PM, Kazimir Majorinc wrote:
> I want to write the function "counted" that generates closures in
> Scheme; I want that after this
> (define f (counted '(x) '(+ x x)))
> f behaves like I wrote
> (define f (let((i 0))
>             (lambda(x) ;first argument
>               (set! i (+ i 1))
>               (display i)
>               (+ x x)))) ;second argument
> and to avoid symbols leaking which happens if I call
> (define f (counted '(i) '(+ i i)))
> How would you do that "idiomatically"?

Idiomatically, one would do this instead:

   (define (counted proc)
     (let ([i 0])
       (lambda args
         (set! i (+ i 1))
         (display i)
         (apply proc args))))

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

because symbols and lists do not adequately represent pieces of Racket 
programs. (See also Eli's macro solution.)


Posted on the users mailing list.