1

返回在 Scheme 中调用了多少次的函数看起来像

(define count
  (let ((P 0))
    (lambda () 
      (set! P (+ 1 P))
      P)))

(list (count) (count) (count) (count)) ==> (list 1 2 3 4)

但是假设我们有一个看起来像这样的表达式

(map ______ lst)

我们希望它评估为

(list 1 2 3 ... n)
where n = (length list)

问题要求我们在空格中使用 lambda 语句,并且不能在空格中使用任何辅助定义,如 (count),所以

(lambda (x) (count))

不被允许。只需将 (count) 替换为之前的定义,如下所示:

(map
 (lambda (x)
   ((let ((P 0))
      (lambda () 
        (set! P (+ 1 P))
        P))))
 L)

也不行。

有什么建议么?

4

3 回答 3

1

你已经完成了 90% 的路。在空白处使用定义的右侧count,并向函数添加一个(忽略的)参数。

于 2013-01-11T02:05:03.067 回答
1

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.

于 2013-01-11T02:41:24.507 回答
-2
(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)

    )
    
)
于 2022-01-09T11:17:51.470 回答