gpt4 book ai didi

functional-programming - 为什么我们在 lisp 解释器中使用序列到表达式的转换?

转载 作者:行者123 更新时间:2023-12-04 10:03:47 25 4
gpt4 key购买 nike

我正在阅读使用 lisp 的 Scheme 方言的 SICP。我的问题是为什么需要如下定义的序列到表达式转换函数,它在条件定义中使用但不在 if 表达式中使用?

(define (sequence->exp seq)
(cond ((null? seq) seq)
((last-exp? seq) (first-exp seq))
(else (make-begin seq))))

(define (make-begin seq) (cons 'begin seq))

以下是不需要序列到表达式转换的 if 表达式的定义:
(define (if? exp) (tagged-list? exp 'if))
(define (if-predicate exp) (cadr exp))
(define (if-consequent exp) (caddr exp))
(define (if-alternative exp)
(if (not (null? (cdddr exp)))
(cadddr exp)
'false))

(define (eval-if exp env)
(if (true? (eval (if-predicate exp) env))
(eval (if-consequent exp) env)
(eval (if-alternative exp) env)))

以下是其谓词确实需要序列到表达式转换的条件的定义。
(define (cond? exp) (tagged-list? exp 'cond))

(define (cond-clauses exp) (cdr exp))

(define (cond-else-clause? clause)
(eq? (cond-predicate clause) 'else))

(define (cond-predicate clause) (car clause))

(define (cond-actions clause) (cdr clause))

(define (cond->if exp) (expand-clauses (cond-clauses exp)))

(define (expand-clauses clauses)
(if (null? clauses)
'false ; no else clause
(let ((first (car clauses))
(rest (cdr clauses)))
(if (cond-else-clause? first)
(if (null? rest)
(sequence->exp (cond-actions first))
(error "ELSE clause isn't last: COND->IF"
clauses))
(make-if (cond-predicate first)
(sequence->exp (cond-actions first))
(expand-clauses rest))))))

最佳答案

if表达式只能计算一个结果表达式或一个替代表达式。但是一个cond expression 计算与为真的条件子句关联的表达式序列。 sequence->exp需要过程将表达式序列转换为单个表达式。通过将序列包装在 begin 中形式,创建一个单独的表达式,它可以作为 if 中的结果或替代表达式求值。表达。
sequence->exp的目的调用贴出的代码是为了方便cond的转换表达到 if表达式;因此,在 cond 中找到的任何表达式序列分支必须在新生成的 if 中转换为单个表达式表达。

关于functional-programming - 为什么我们在 lisp 解释器中使用序列到表达式的转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61692068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com