Scheme 参数存储为成对而不是数字?

Scheme 参数存储为成对而不是数字?,scheme,lisp,Scheme,Lisp,在大学里,我们正在Scheme中构建一个Scheme解释器。在下面的代码中,您可以看到加号运算符的实现 #lang racket (define (EVAL e) (if (pair? e) ;if its a pair its a function -> call EVALFunctionCall (EVALFunctionCall e) (null))) ;null - other cases are not implemented (def

在大学里,我们正在Scheme中构建一个Scheme解释器。在下面的代码中,您可以看到加号运算符的实现

#lang racket

(define (EVAL e)
    (if (pair? e) ;if its a pair its a function -> call EVALFunctionCall
        (EVALFunctionCall e)
        (null))) ;null - other cases are not implemented

(define (EVALFunctionCall e)
    (if (eq? (car e) '+) ;if its + its addition -> call EVALPlus
        (EVALPlus (cdr e))
        (null))) ;null - other cases are not implemented

(define (EVALPlus argList) 
    ;for debugging
    (display (car argList))(display "\n")
    (display (cdr argList))(display "\n")
    (display (car (cdr argList)))(display "\n")
    (display (cdr (cdr argList)))(display "\n")

    (+ (car argList) (cdr argList)))
(EVAL'(+12))
应计算为
3
。但事实并非如此。相反,我得到了一个错误。 这是因为
(cdr argList)
(我传递给+-函数的第二个参数)不是一个数字,而是一对。为调试打印输出而添加的显示:

1
(2)
2
()

我很确定这就是教授在课上展示的代码(这很有效)。那我做错了什么?我的教授是否可能使用另一种scheme方言,它可以像
(+(12))
一样保存(+12))
,而不是像
(+(1(2 null))

那么,显而易见的解决方案是:

(define (EVALPlus argList)
   (apply + argList))
然而,由于该练习是关于实现方案解释器的,因此这可能是欺骗;-)

那么,一个简单的累积总和呢:

(define (EVALPlus argList)
   (cond ((null? argList) 0)
         ((null? (cdr argList)) (car argList))
         (#t (+ (car argList) (EVALPlus (cdr argList))))))
或者,如果您不被允许
cond

(define (EVALPlus argList)
   (if (null? argList) 0
      (if (null? (cdr argList)) (car argList)
         (+ (car argList) (EVALPlus (cdr argList))))))
一如既往,请注意特殊情况:

(EVAL '(+)) ; no argument
=> 0
(EVAL '(+ 42)) ; only one argument
=> 42
(EVAL '(+ 1 3 5 7 9)) ; n arguments
=> 25

希望有帮助。

您的代码中有一个小错误,请在
EVALPlus
过程中尝试:

(+ (car argList) (car (cdr argList)))

请记住,
cdr
检索下一个列表,而不是下一个元素。获取下一个列表后,我们调用
car
获取其第一个元素。

谢谢!当然,我的教授就是这样实现的。我真可耻,我没有发现自己的错误。