在 SICP 中将 lambda 用于 cons/car/cdr 定义 [英] Use of lambda for cons/car/cdr definition in SICP
问题描述
当我在 SICP 中遇到以下关于 cons 和 car 的替代"定义时,我才开始觉得我对 lambda 在球拍和方案中的使用有一种模糊的理解
I was just beginning to feel I had a vague understanding of the use of lambda in racket and scheme when I came across the following 'alternate' definitions for cons and car in SICP
(define (cons x y)
(lambda (m) (m x y)))
(define (car z)
(z (lambda (p q) p)))
(define (cdr z)
(z (lambda (p q) q)))
就我的一生而言,我就是无法解析它们.
For the life of me I just cannot parse them.
有人能解释一下如何以一种对新手来说有意义的方式解析或扩展这些吗?
Can anybody explain how to parse or expand these in a way that makes sense for total neophytes?
推荐答案
这是一种表示数据的有趣方式:作为函数.请注意,这cons
的定义返回一个 lambda
,它 关闭 参数 x
和 y
,在里面捕获它们的值.还要注意返回的 lambda接收一个 function m
作为参数:
This is an interesting way to represent data: as functions. Notice that this
definition of cons
returns a lambda
which closes over the parameters x
and y
, capturing their values inside. Also notice that the returned lambda
receives a function m
as a parameter:
;creates a closure that "remembers' 2 values
(define (cons x y) (lambda (m) (m x y)))
;recieves a cons holding 2 values, returning the 0th value
(define (car z) (z (lambda (p q) p)))
;recieves a cons holding 2 values, returning the 1st value
(define (cdr z) (z (lambda (p q) q)))
在上面的代码中z
是一个闭包,和cons
创建的一样,在我们传递给它的过程主体another lambda
作为参数,还记得 m
吗?就是这样!它所期望的功能.
In the above code z
is a closure, the same that was created by cons
, and in
the body of the procedure we're passing it another lambda
as parameter,
remember m
? it's just that! the function that it was expecting.
理解了上面的内容,很容易看出car
和cdr
是如何工作的;让我们剖析 car
, cdr
是如何被解释器一次一步地求值的:
Understanding the above, it's easy to see how car
and cdr
work; let's
dissect how car
, cdr
is evaluated by the interpreter one step at a time:
; lets say we started with a closure `cons`, passed in to `car`
(car (cons 1 2))
; the definition of `cons` is substituted in to `(cons 1 2)` resulting in:
(car (lambda (m) (m 1 2)))
; substitute `car` with its definition
((lambda (m) (m 1 2)) (lambda (p q) p))
; replace `m` with the passed parameter
((lambda (p q) p) 1 2)
; bind 1 to `p` and 2 to `q`, return p
1
总结:cons
创建了一个记住两个值,car
"的闭包接收该闭包并将其传递给作为选择器的函数第零个值,cdr
充当第一个值的选择器.钥匙这里要理解的一点是 lambda
充当关闭.这有多酷?我们只需要存储和检索任意数据的函数!
To summarize: cons
creates a closure that "remembers' two values, car
receives that closure and passes it along a function that acts as a selector for
the zeroth value, and cdr
acts as a selector for the 1st value. The key
point to understand here is that lambda
acts as a
closure.
How cool is this? we only need functions to store and retrieve arbitrary data!
car
& 的嵌套组合cdr
被定义为最多 4 个深度 在大多数 LISP 中.例子:
Nested Compositions of car
& cdr
are defined up to 4 deep in most LISPs. example:
(define caddr (lambda (x) (car (cdr (cdr x)))))
这篇关于在 SICP 中将 lambda 用于 cons/car/cdr 定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!