在 Scheme 的条件表达式中使用 define
Using define in a conditional expression in Scheme
在 Scheme 中,过程定义的一般形式是:
(define (<name> <parameters>) <body>)
其中 <body> 接受表达式序列,允许这种过程定义:
> (define (f) 1 2 3)
> (f)
3
同样,条件表达式的一般形式是:
(cond (<predicate> <consequent>) (<predicate> <consequent>) … (<predicate> <consequent>))
其中 <consequent> 在每个子句中接受一个表达式序列,允许这种条件表达式:
> (cond (#t 1 2 3))
3
但是为什么我不能像在过程定义的主体中那样在条件表达式的子句后缀中使用 define
?
比较:
> (define (f) (define x 1) (define y 1) (define z 1) (+ x y z))
> (f)
3
与:
> (cond (#t (define x 1) (define y 1) (define z 1) (+ x y z)))
ERROR on line 1: unexpected define: (define x 1)
注意。 — 我在 MacOS 10.15.2 上使用 Chibi-Scheme 0.8.0 实现。
正如@Barmar 指出的那样,定义 不是表达式,但有两种上下文都允许(参见第 5.1 节)。 R7RS,强调我的):
- 在程序的最外层;
- 正文开头。
A Scheme program consists of one or more import declarations followed by a sequence of expressions and definitions. Import declarations specify the libraries on which a program or library depends; a subset of the identifiers exported by the libraries are made available to the program. Expressions are described in chapter 4. Definitions are either variable definitions, syntax definitions, or record-type definitions, all of which are explained in this chapter. They are valid in some, but not all, contexts where expressions are allowed, specifically at the outermost level of a ⟨program⟩ and at the beginning of a ⟨body⟩.
这就是为什么 define
允许出现在过程定义的主体中,但不允许出现在条件表达式的子句的结果中,因为它不是主体。
在 Scheme 中,过程定义的一般形式是:
(define (<name> <parameters>) <body>)
其中 <body> 接受表达式序列,允许这种过程定义:
> (define (f) 1 2 3)
> (f)
3
同样,条件表达式的一般形式是:
(cond (<predicate> <consequent>) (<predicate> <consequent>) … (<predicate> <consequent>))
其中 <consequent> 在每个子句中接受一个表达式序列,允许这种条件表达式:
> (cond (#t 1 2 3))
3
但是为什么我不能像在过程定义的主体中那样在条件表达式的子句后缀中使用 define
?
比较:
> (define (f) (define x 1) (define y 1) (define z 1) (+ x y z))
> (f)
3
与:
> (cond (#t (define x 1) (define y 1) (define z 1) (+ x y z)))
ERROR on line 1: unexpected define: (define x 1)
注意。 — 我在 MacOS 10.15.2 上使用 Chibi-Scheme 0.8.0 实现。
正如@Barmar 指出的那样,定义 不是表达式,但有两种上下文都允许(参见第 5.1 节)。 R7RS,强调我的):
- 在程序的最外层;
- 正文开头。
A Scheme program consists of one or more import declarations followed by a sequence of expressions and definitions. Import declarations specify the libraries on which a program or library depends; a subset of the identifiers exported by the libraries are made available to the program. Expressions are described in chapter 4. Definitions are either variable definitions, syntax definitions, or record-type definitions, all of which are explained in this chapter. They are valid in some, but not all, contexts where expressions are allowed, specifically at the outermost level of a ⟨program⟩ and at the beginning of a ⟨body⟩.
这就是为什么 define
允许出现在过程定义的主体中,但不允许出现在条件表达式的子句的结果中,因为它不是主体。