Computing the sum of the first n numbers in lisp

Tag: lisp , common-lisp Author: Kolyen Date: 2013-12-25
(defun sum(n)
  (cond
    ((= n 0) 0)
    ((= n 1) 1)
    (T (+ n sum (- n 1)))))

If I call (sum 4) it should show 10 but it gives me an error : Variable SUM has no value

try replacing sum ( -n 1) with (sum (-n 1))
sum in your function is a variable. You might want to call the function sum? Think about using the Lisp syntax for calling functions...
On another note, what happens if you call (sum -1)? ;-)
This question appears to be off-topic because it is about a small typographical error (sum (- n 1) instead of (sum (- n 1))), and the content of the question isn't likely to help future users with the same problem find it.

Best Answer

Common Lisp is a Lisp-2, which means that variables and functions are in distinct namespaces.

There is a function sum, but there is no variable sum, at the point where you're using it as a variable: (+ n sum (- n 1)).

Your intention may have been to write (+ n (sum (- n 1))) instead, calling the function sum recursively:

(defun sum (n)
  (cond ((= n 0) 0)
        ((= n 1) 1)
        (T (+ n (sum (- n 1))))))

(If you wanted to refer to the function sum as a value, e.g. to pass it to another function, you would write #'sum.)

comments:

It's working Thank you!
Why 2 base cases? (defun sum (n) (if (= n 0) 0 (+ n (sum (- n 1))))) should do.
@uselpa Sure, I was just making an exact copy of the asker's code apart from fixing formatting and the issue they were asking about.
The question was more to the OP, although you could have suggested it too imo.