2

I read in Let over Lambda about lexical clojures and this code sample was given for Common Lisp:

(let ((counter 0))
  (lambda () (incf counter)))

I tried writing this in Racket as:

(let ((counter 0))
  (lambda() (+ counter 1)))

When I call it in the REPL as counter it gives me the error:

counter: undefined;
 cannot reference an identifier before its definition

As far as I understood, mixing let/set with lambda gives you the ability to store in a lambda some state that can be processed by other functions in the same manner that human memory can be processed and changed by the input from the senses. I'm interested in having in my LISP programs parts of code that are changed by their interaction with other function. Even if this isn't done by lambda, I still want to understand it(the lambda function) because it appears to be an important part of Racket and other LISP dialects.

4

2 回答 2

5

(incf x)在 Common Lisp 中不等同于(+ x 1)在 Racket 中,而是先递增x: (set! x (+ x 1)),然后返回新值的组合。

所以,如果你想在 Racket 中定义一个类似的函数,你可以这样写,例如:

(define count
  (let ((counter 0))
    (lambda () (begin (set! counter (+ counter 1)) counter))))

(count)    ; returns 1

(count)    ; returns 2
于 2016-04-08T16:01:13.747 回答
0

使用方案/球拍,您需要使用Lisp 函数set!代替incf它(顺便说一句,set!不返回新值,不像infc)。

于 2016-04-08T16:00:39.417 回答