我是初学者,我正在尝试自学Common Lisp,在我的自学期间,我编写了一个函数,我相信它应该适用于递归添加两个参数。但是,该功能总是失败。那是为什么?
(defun sum (n m)
;;;Returns the sum of n and m using recursion
(cond ((eq m 0) n))
(sum (1+ n) (1- m)))
据我了解,它应该连续加1到n,同时递减m直到m为0,此时递归加法完成
答案 0 :(得分:5)
这种添加真的很奇怪的用例,但我会解释你的错误在哪里:
(defun sum (n m)
;;;Returns the sum of n and m using recursion
(cond ((eq m 0) n)) ;; <= This line is ignored, you not returnin N.
(sum (1+ n) (1- m))) ;; <= this will be called forever
你应该写:
(defun sum (n m)
"Recursively increment N and decrement M untill M = 0"
(if (= m 0) ;; don't use EQ for numbers, use EQL or =.
n
(sum (1+ n) (1- m)))) ;; Otherwise recursive call
让我们跟踪它以了解它是如何工作的:
CL-USER> (sum 0 10)
0: (SUM 0 10)
1: (SUM 1 9)
2: (SUM 2 8)
3: (SUM 3 7)
4: (SUM 4 6)
5: (SUM 5 5)
6: (SUM 6 4)
7: (SUM 7 3)
8: (SUM 8 2)
9: (SUM 9 1)
10: (SUM 10 0)
10: SUM returned 10
9: SUM returned 10
8: SUM returned 10
7: SUM returned 10
6: SUM returned 10
5: SUM returned 10
4: SUM returned 10
3: SUM returned 10
2: SUM returned 10
1: SUM returned 10
0: SUM returned 10
10
如果你会接受建议 - 不要尝试用递归来做这些奇怪的事情,如果你想学习如何使用它,试试一些自然递归的情况,如阶乘,斐波纳契,树处理等
答案 1 :(得分:5)
我认为你有两个简单的拼写错误:
t
子句中缺少cond
。 你可能意味着:
(defun sum (n m)
(cond
((eq m 0) n) ; here you had one parenthesis too many
(t (sum (1+ n) (1- m))))) ; here you were missing the `t` symbol