灯下 登录
计算机科学 / SICP / 4.1.2 Representing Expressions

Exercise 4.5 · 习题

Exercise 4.5: Scheme allows an additional syntax
for cond clauses, (⟨test⟩ => ⟨recipient⟩). If
⟨test⟩ evaluates to a true value, then ⟨recipient⟩ is evaluated.
Its value must be a procedure of one argument; this procedure is then invoked
on the value of the ⟨test⟩, and the result is returned as the value of
the cond expression. For example

(cond ((assoc 'b '((a 1) (b 2))) => cadr)
(else false))

returns 2. Modify the handling of cond so that it supports this

extended syntax.

练习 4.5:Scheme 为 cond 子句提供了一种附加语法 (⟨test⟩ => ⟨recipient⟩)。若 ⟨test⟩ 求值为真值,则对 ⟨recipient⟩ 求值,其结果必须是一个单参数过程;该过程随即以 ⟨test⟩ 的值为参数被调用,调用结果作为整个 cond 表达式的值返回。例如

(cond ((assoc 'b '((a 1) (b 2))) => cadr)
(else false))

返回 2。请修改对 cond 的处理,使其支持这种扩展语法。

Racket #lang sicp
(cond ((assoc 'b '((a 1) (b 2))) => cadr)
 (else false))