我在Scheme中有以下代码:
(define (processExpression lst)
(define operand (car lst))
(define operator1 (cadr lst))
(define operator2 (caddr lst))
(if (list? operand)
(begin
(display "Invalid syntax! Erroring out!")
(quit)
)
)
(if (and (number? operator1) (number? operator2))
;The list was of the form (operand c1 c2)
(simplePrefix lst)
)
(if (and (list? operator1) (number? operator2))
(begin
(list operand operator2 (processExpression operator1))
)
)
)
(define (simplePrefix lst)
(let (
(operand (car lst))
(operator1 (cadr lst))
(operator2 (caddr lst)))
(list operator1 operand operator2)
)
)
(display "Please enter a valid s-expression")
(let ((input (read)))
(display (simplePrefix input))
)
此代码采用s-expression并根据某些规则对其进行转换。一条规则应该是表达式(+(+ 1 2)2)应该返回(+ 2(1 + 2))。
目前,当我使用该表达式调用此代码时,我会返回结果" #undef>"但我不知道为什么。代码应该在表达式的(+ 1 2)部分调用simplePrefix函数并返回(1 + 2),但它不会。有谁理解为什么?
答案 0 :(得分:2)
的值
(if condition
something)
如果条件为false,则未定义,因为 if 表单中没有 else 部分。在R5RS版本的Scheme中,陈述了这一点(强调添加):
4.1.5 Conditionals
语法:
(if <test> <consequent> <alternate>)
语法:(if <test> <consequent>)
语法:<Test>
,<consequent>
和<alternate>
可以是任意表达式。语义:if表达式的计算方法如下:首先,&lt; test&gt;被评估。如果它产生一个真值(见章节) 6.3.1),然后&lt;结果&gt;被评估并返回其值。否则&lt; alternate&gt;被评估及其价值 是(是)返回。 如果&lt; test&gt;产生假值而不是 &LT;备用&GT;指定,然后表达式的结果是 未指定的。强>
(if (> 3 2) 'yes 'no) ===> yes (if (> 2 3) 'yes 'no) ===> no (if (> 3 2) (- 3 2) (+ 3 2)) ===> 1
如果您尝试这样的话,一些类似Scheme的语言(例如,Racket)实际上会警告您:
Welcome to Racket v6.1.
> (if #t
(display "hello"))
stdin::1: if: missing an "else" expression
in: (if #t (display "hello"))
context...:
在Common Lisp中,else部分是可选的,如果没有提供,则定义为 nil :
This is SBCL 1.2.4.58-96f645d, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
* (if t
(print 'hello))
HELLO
HELLO
* (if nil
(print 'hello))
NIL
答案 1 :(得分:0)
表达式
(if condition result)
等同于
if condition
return result
用其他语言。
它没有返回值,它有一个值。
如果条件为假,则该值未定义
如果序列中跟随其他表达式,则忽略该值并计算以下表达式。
评估函数应用程序的结果是函数体中最后一个表达式的值
(define (foo)
(if (= 1 1)
"one is one")
"I am still here")
> (foo)
"I am still here"
这两个加在一起会导致您遇到的错误。