在Lisp中将变量与字符进行比较



我是lisp编程的新手,我正在尝试将变量(比如op(与字符+、-、*、/进行比较。但在我写的每一个方面,都没有出现正确的结果。我如何重写以下代码:

(defun evaluate(op o1 o2)
(cond
( (string= op `+) (+ o1 o2))
( (string= op `-) (- o1 o2))
( (string= op `*) (* o1 o2))
( (string= op `/) (/ o1 o2))
)
)

输入为:

(print (calculate `(- * + 4 3 2 5)))

所以我在函数中得到了运算符字符。不要介意数字。这里是计算函数。

(defun calculate (l)
(if (and (numberp (car l)) (not (null l)) )
(car l)
( evaluate (car l) (calculate (cdr l) ) 
(calculate (cdr l) ) )
)
)

写入calculate的方式计算(- (* (+ 4 4) (+ 4 4)) (* (+ 4 4) (+ 4 4))),即0。我不知道你期待什么,但让我们看看跟踪(SO>是repl提示符(:

SO> (trace evaluate calculate)
(EVALUATE CALCULATE)
SO> (calculate '(- * + 4 3 2 5))
0: (SO::CALCULATE (- * + 4 3 2 5))
1: (SO::CALCULATE (* + 4 3 2 5))
2: (SO::CALCULATE (+ 4 3 2 5))
3: (SO::CALCULATE (4 3 2 5))
3: CALCULATE returned 4
3: (SO::CALCULATE (4 3 2 5))
3: CALCULATE returned 4
3: (SO::EVALUATE + 4 4)
3: EVALUATE returned 8
2: CALCULATE returned 8
2: (SO::CALCULATE (+ 4 3 2 5))
3: (SO::CALCULATE (4 3 2 5))
3: CALCULATE returned 4
3: (SO::CALCULATE (4 3 2 5))
3: CALCULATE returned 4
3: (SO::EVALUATE + 4 4)
3: EVALUATE returned 8
2: CALCULATE returned 8
2: (SO::EVALUATE * 8 8)
2: EVALUATE returned 64
1: CALCULATE returned 64
1: (SO::CALCULATE (* + 4 3 2 5))
2: (SO::CALCULATE (+ 4 3 2 5))
3: (SO::CALCULATE (4 3 2 5))
3: CALCULATE returned 4
3: (SO::CALCULATE (4 3 2 5))
3: CALCULATE returned 4
3: (SO::EVALUATE + 4 4)
3: EVALUATE returned 8
2: CALCULATE returned 8
2: (SO::CALCULATE (+ 4 3 2 5))
3: (SO::CALCULATE (4 3 2 5))
3: CALCULATE returned 4
3: (SO::CALCULATE (4 3 2 5))
3: CALCULATE returned 4
3: (SO::EVALUATE + 4 4)
3: EVALUATE returned 8
2: CALCULATE returned 8
2: (SO::EVALUATE * 8 8)
2: EVALUATE returned 64
1: CALCULATE returned 64
1: (SO::EVALUATE - 64 64)
1: EVALUATE returned 0
0: CALCULATE returned 0
0

最后一个0就是结果。在这些数字中,只有第一个被触摸过,我想你也打算使用其他数字。

需要指出的是,在calculate内部对(calculate (cdr l))的两次调用将始终产生相同的结果。

旁注:

  • 使用标准格式(例如,请参阅。http://www.gigamonkeys.com/book/syntax-and-semantics.html#formatting-lisp代码(
  • 使用撇号',而不是反勾号。后者有不同的用途
  • 理解符号和字符串之间的区别

相关内容

  • 没有找到相关文章

最新更新