使用递归LISP计算的总和

时间:2016-01-31 16:42:14

标签: lisp

我是LISP的初学者。我遇到了以下错误** - IF:变量SUM-REC没有值,但不知道如何解决它。这是我的代码。

  (defun sum-rec (n) 
  (if (not (eq n 0))

    (+ (sum-rec(-n 1) )n )
    0
    )

(format t "ans = ~a~%" (sum-rec 4))

2 个答案:

答案 0 :(得分:2)

请勿使用eq来比较数字,因为eq会比较对象,并且无法保证这对数字符合预期效果。使用eql=,或者在这种情况下使用/=代替。

函数调用表示为(func p1 p2 ...),而不是func(p1 p2 ...)

所以正确的代码是

(defun sum-rec (n) 
  (if (/= n 0)
      (+ (sum-rec (- n 1)) n)
      0))

测试:

CL-USER> (format t "ans = ~a~%" (sum-rec 4))
ans = 10
NIL

CL-USER> (+ 1 2 3 4)
10

答案 1 :(得分:-1)

  1. 检查括号:它们是不平衡的。
  2. 请正确格式化代码:有助于阅读并查找错误。
  3. 在Lisp中,空格很重要:它将项目分开。在<defs> <lineargradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%"> <stop offset="0%" style="stop-color:rgb(255,255,255);stop-opacity:0"> <animate attributeName="stop-opacity" values="0; 1" begin="middle1.end" dur="1s" fill="freeze" /> </stop> <stop offset="40%" style="stop-color:rgb(255,255,255);stop-opacity:0"> <animate attributeName="stop-opacity" values="0; 1" begin="2000ms" dur="1s" id="middle1" fill="freeze" /></stop> <stop offset="70%" style="stop-color:rgb(255,255,255);stop-opacity:0"> <animate attributeName="stop-opacity" values="0; 1" begin="800ms" dur="2s" id="middle" fill="freeze" /></stop> <stop offset="100%" style="stop-color:rgb(255,255,255);stop-opacity:0"> <animate attributeName="stop-opacity" values="0; 1" dur="1s" id="down" fill="freeze" /></stop> </lineargradient> </defs>中,(sum-rec (-n 1))-之间缺少空格。 Lisp会将其作为应用于n的函数-n来阅读,这显然不是那里的意思。
  4. 修好后,一切正常:

    1