SICP 练习 2.04

SICP Exercise 2.04

正在阅读SICP我现在在练习2.04,这是conscarcdr的程序表示,书中给出如下:

(define (cons x y)
  (lambda (m)
    (m x y)))

(define (car z)
  (z
    (lambda (p q)
      (p))))

请注意,对于 运行,我在代码中使用 racket 和以下序言:

#lang racket
(define (Mb-to-B n) (* n 1024 1024))
(define MAX-BYTES (Mb-to-B 64))
(custodian-limit-memory (current-custodian) MAX-BYTES)

我也试过#lang scheme没用。

这是我的理解:

关于cons

关于car

用法

起初我尝试了以下方法:

(car (cons 1 2))
(car (cons 2 3))
(car (cons (cons 1 1) (cons 2 2)))
(car (car (cons (cons 1 1) (cons 2 2))))

然而,这会导致错误:

:racket -l errortrace -t exercise-2.04-procedural-representation-of-pairs.rkt 
application: not a procedure;
 expected a procedure that can be applied to arguments
  given: 1
  arguments...: [none]
  errortrace...:
   /home/xiaolong/development/LISP/Racket/SICP/exercise-2.04-procedural-representation-of-pairs.rkt:24:6: (p)
   /home/xiaolong/development/LISP/Racket/SICP/exercise-2.04-procedural-representation-of-pairs.rkt:33:0: (car (cons 1 2))
  context...:
   /home/xiaolong/development/LISP/Racket/SICP/exercise-2.04-procedural-representation-of-pairs.rkt: [running body]

我无法理解我的代码有什么问题,所以我在其他人的解决方案中查找了一些使用示例。一个在 http://community.schemewiki.org/?sicp-ex-2.4:

(define x (cons 3 4))
(car x)

但令我惊讶的是,它不起作用! wiki中的解决方案似乎是错误的。我收到以下错误:

application: not a procedure;
 expected a procedure that can be applied to arguments
  given: 3
  arguments...: [none]
  errortrace...:
   /home/xiaolong/development/LISP/Racket/SICP/exercise-2.04-procedural-representation-of-pairs.rkt:24:6: (p)
   /home/xiaolong/development/LISP/Racket/SICP/exercise-2.04-procedural-representation-of-pairs.rkt:42:0: (car x)
  context...:
   /home/xiaolong/development/LISP/Racket/SICP/exercise-2.04-procedural-representation-of-pairs.rkt: [running body]

我做错了什么?

您的代码有错误。而不是:

(define (car z)
  (z
    (lambda (p q)
      (p))))

你应该写(见book):

(define (car z)
  (z
    (lambda (p q)
      p)))

注意最后一行p没有括号。

消息:application: not a procedure 表示 p 不是过程(它实际上是一个数字),而使用符号 (p) 时,您将其称为无参数过程。