sicp每日一题[2.4]

Exercise 2.4

Here is an alternative procedural representation of pairs. Forthisrepresentation, verify that (car (cons x y)) yields x for any objects x and y.

(define (cons x y)
 (lambda (m) (m x y)))
(define (car z)
 (z (lambda (p q) p)))

Whatisthe corresponding definition of cdr? (Hint: To verify that this works, make use of the substitution model of Section 1.1.5.)


这道题很简单,只需要把 car 改一个字母就行。

; 返回值是一个单参数的函数,它会把 cons 函数的两个数传给返回值函数
(define (cons x y)
  (lambda (m) (m x y)))

; 如果 z 是由 cons 函数创建的数据对,则 z 会把 (lambda (p q) p)) 作为参数
(define (car z)
  (z (lambda (p q) p)))

(define (cdr z)
  (z (lambda (p q) q)))


(define z (cons 3 4)) 
(car z) 
(cdr z) 

; 执行结果
3
4

; applicative-order
; (car (cons x y)) 
; (car (lambda (m) (m x y))) 
; ((lambda (m) (m x y)) (lambda (p q) p)) 
; ((lambda (p q) p) x y) 
; x 
posted @ 2024-09-10 10:42  再思即可  阅读(3)  评论(0编辑  收藏  举报