A function that returns how many times it has been called in Scheme would look like
(define count
(let ((P 0))
(lambda ()
(set! P (+ 1 P))
P)))
(list (count) (count) (count) (count)) ==> (list 1 2 3 4)
But suppose that we have an expression that looks like this
(map ______ lst)
and we want that to evaluate to
(list 1 2 3 ... n)
where n = (length list)
The problem requires we use a lambda statement in the blank, and we cannot use any auxiliary definitions like (count) in the blank, so
(lambda (x) (count))
is not allowed. Simply replacing (count) with the previous definition like this:
(map
(lambda (x)
((let ((P 0))
(lambda ()
(set! P (+ 1 P))
P))))
L)
doesn't work either.
Any suggestions?
You're very, very close to a correct solution! in the code in the question just do this:
lambda
is erroneous, delete that line and the corresponding closing parenthesislambda
is the one that will eventually get passed to the map
procedure, so it needs to receive a parameter (even though it's not actually used)let
formIt all boils down to this: the lambda
that gets passed to map
receives a parameter, but also encloses the P
variable. The let
form defines P
only once in the context of the passed lambda
, and from that point on the lambda
"remembers" the value of P
, because for each of the elements in the list the same P
is used.