Using define in a conditional expression in Scheme
https://softwareengineering.stackexchange.com/questions/403977
-
06-03-2021 - |
質問
In Scheme, the general form of a procedure definition is:
(define (<name> <parameters>) <body>)
where <body> accepts a sequence of expressions, allowing this kind of procedure definitions:
> (define (f) 1 2 3)
> (f)
3
Likewise, the general form of a conditional expression is:
(cond (<predicate> <consequent>) (<predicate> <consequent>) … (<predicate> <consequent>))
where <consequent> in each clause accepts a sequence of expressions, allowing this kind of conditional expressions:
> (cond (#t 1 2 3))
3
But why can’t I use define
in a clause’s consequent of a conditional expression like in the body of a procedure definition?
Compare:
> (define (f) (define x 1) (define y 1) (define z 1) (+ x y z))
> (f)
3
with:
> (cond (#t (define x 1) (define y 1) (define z 1) (+ x y z)))
ERROR on line 1: unexpected define: (define x 1)
Note. — I am using the Chibi-Scheme 0.8.0 implementation on MacOS 10.15.2.
解決
define
can only be used at either the top-level, or at the beginning of a body
. It cannot be used in other places where expressions can be used. Here is the relevant quote from R5RS:
Definitions are valid in some, but not all, contexts where expressions are allowed. They are valid only at the top level of a <program> and at the beginning of a <body>.
The cases of a cond
are not body
s, and so you cannot put a define
there.