程序和lambda

时间:2015-03-05 12:01:36

标签: scheme procedures

(define (p-cons x y)
 (lambda (proc) (proc x y)))

(define (p-car proc)
(proc (lambda (p q) p)))

> (p-car(p-cons "foo" "bar"))
"foo"

这段代码如何工作? 这是一个自制的"计划中的缺点和汽车版本。 我似乎无法理解为什么" p-cons"工作。

(lambda (proc) (proc x y)))
(proc (lambda (p q) p)))
These two sentences makes no sense to me. 
How does (lambda (proc) (proc x y))) make it work as cons?

1 个答案:

答案 0 :(得分:1)

这通过将所有相关状态保持在闭包变量中来起作用。考虑

(define (p-cons x y)
  ;; "x" and "y" will be "closed over" and their values
  ;; are later available, whenever someone calls the 
  ;; anonymous lambda function, which we return here: 
  (lambda (accessor) 
    ;; Call the accessor, and pass all our hidden state
    ;; along. The accessor will select, whatever it needs,
    ;; and we simply return, whatever the accessor returned
    (apply accessor x y '())))

(define (p-car pseudo-cons)
  (apply pseudo-cons 
         ;; Is called by the "pseudo-cons" and receives the
         ;; full hidden state. Selects from it, what it wants
         ;; to return (here, the first "field")
         (lambda (state-x state-y) state-x) 
         '()))

(define (p-cdr pseudo-cons) 
  (apply pseudo-cons 
         ;; Is called by the "pseudo-cons" and receives the
         ;; full hidden state. Selects from it, what it wants
         ;; to return (here, the second "field")
         (lambda (state-x state-y) state-y) 
         '()))

让我们检查一下。当我们做的时候

(define some-p-cons (p-cons 1 2))

some-p-cons的值是一个过程,它需要一个参数(我们稍后会讨论)。更重要的是,它是一个“闭包”,这是一个具有一些隐藏状态的过程。在我们的示例中,此隐藏状态由提供给x的{​​{1}}和y参数值组成。例子:

p-cons

基本上,(p-cons 1 2) ==> some procedure (hidden state x = 1 and y = 2) (p-cons 'a 'b) ==> some procedure (hidden state x = a and y = b) (p-cons "hello" ()) ==> some procedure (hidden state x = "hello" and y = ()) 就像一条记录 - 如果有办法以某种方式提取隐藏状态(或者,它将是一个非常无用的记录......)

这就是闭包的单个参数(上面名为p-cons)发挥作用的地方。使用完全隐藏闭包状态(accessorx)调用访问器并选择要返回的这些值中的哪一个。 y访问器返回第一个(p-car)值,x访问器返回第二个(p-cdr)值。让我们来看看:

致电

y

产生一些对象

(p-cons 1 2)

(当场制作的符号)。当我们将#<closure (lambda (accessor) (accessor x y)) with hidden state x=1, y=2> 应用于它时

p-car

会发生什么,(p-car #<closure (lambda (accessor) (accessor x y)) with hidden state x=1, y=2>) 本身会调用“伪缺点”(它本身就是一个过程),传递一个访问器函数,它选择隐藏状态的相应位。 p-car函数可以

p-car

现在,球回到了“伪利弊”的关闭。它接受所有隐藏状态,并将其传递给访问者:

(apply #<closure (lambda (accessor) (accessor x y)) with hidden state x=1, y=2>
       (lambda (state-x state-y) state-x)  ;; anonymous accessor function
       ())

忍受我,我们几乎就在那里......存取者检查它所获得的状态位,并选择,无论它想要返回什么。对于(apply (lambda (state-x state-y) state-x) ;; anonymous accessor function x ;; from hidden state, value is 1 in the example y ;; from hidden state, value is 2 in the example ()) 访问者,我们需要第一个字段的值,因此,这就是我们返回的内容。

p-car并不是真的有必要,但我觉得在本次论述中明确说明它们更清楚了)

我们甚至可以定义一个函数,它将我们的“伪锥形”变成真实的:

apply

在这里,我们“滥用”内置过程(define p-cons->pair (pcons) (apply pcons cons '())) 作为我们的访问器函数,它不是简单地选择它的两个参数中的一个,而是将两者都放在一个常规的方案对中。