Question

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?

Was it helpful?

Solution

You're very, very close to a correct solution! in the code in the question just do this:

  1. The outermost lambda is erroneous, delete that line and the corresponding closing parenthesis
  2. The innermost lambda 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)
  3. Delete the outermost parenthesis surrounding the let form

It 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.

OTHER TIPS

You're 90% of the way there. Use the right-hand-side of your count definition in the blank, and add an (ignored) argument to the function.

(define add-stat-var
    
    (let ( (P '()) )
        (lambda (x1) 
            (if (equal? x1 "ResetStatVar") (set! P '()) (set! P (cons x1 P)))
        P
        ) ;lambda
      
    ) ;let
      
) ;define

(define (test-add-stat-var x)

    (let* ( (result '()) )
    
            (set! result (add-stat-var 12))
            (set! result (add-stat-var 14))
            (set! result (add-stat-var 16))
            
            (display (add-stat-var x)) (newline)
            
            (set! result (add-stat-var "ResetStatVar"))
            
            (display (cdr (add-stat-var x))) (newline)

    )
    
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top