Ok, I'm been learning COMMON LISP programming and I'm working on a very simple program to calculate a factorial of a given integer. Simple, right?
Here's the code so far:
(write-line "Please enter a number...") (setq x (read)) (defun factorial(n) (if (= n 1) (setq a 1) ) (if (> n 1) (setq a (* n (factorial (- n 1)))) ) (format t "~D! is ~D" n a) ) (factorial x) Problem is, when I run this on either CodeChef or Rexter.com, I get a similar error: "NIL is NOT a number."
I've tried using cond instead of an if to no avail.
As a side note, and most bewildering of all, I've seen a lot of places write the code like this:
(defun fact(n) (if (= n 1) 1 (* n (fact (- n 1))))) Which doesn't even make sense to me, what with the 1 just floating out there with no parentheses around it. However, with a little tinkering (writing additional lines outside the function) I can get it to execute (equally bewildering!).
But that's not what I want! I'd like the factorial function to print/return the values without having to execute additional code outside it.
What am I doing wrong?
factorialreturn?xis undefined,ais undefined, I/O buffer not emptied afterwrite-line.