I've been learning Common Lisp and really enjoying it. The two crucial bits of advice to help you get started are:
I've typed in a bit of code, using RETURN instead of Ctrl-j, so the auto-indent hasn't happened.
(defun factorial (n) (let ((product 1)) (loop for i from 1 to n do (setf product (* i product))) product))No matter. I mark the function with the mouse and do Ctrl-Meta-\. Emacs puts in the indentation for me, and my code looks like this
(defun factorial (n)
(let ((product 1))
(loop for i from 1 to n
do (setf product
(* i product)))
product))
Notice that product lines up under loop, and both are
indented relative to let, so you know that product is inside
the scope of the let, without having to check how many
parenthesises you have.
Ctrl-Meta-x sends the definition to the REPL, which echoes the name of the function - FACTORIAL. Ctrl-x o takes me to the other window and I try it out.
(factorial 5) => 120Well, maybe. I ask the REPL, typing (* 1 2 3 4 5) instead of 1*2*3*4*5, and it confirms 120.
Now I can save the file with Ctrl-x Ctrl-s. Once it is saved to disk I can compile it with the file compiler, invoking it from the REPL with (compile-file "/home/alan/learning/lisp/first-try.lisp") If I load first-try.x86f I'll be running compiled code. With CMUCL that is often a thousand times faster. Notice the sequence: edit - run - edit - run - compile. You are probably used to: edit - compile - edit - compile - run.
Common Lisp is multi-paradigm. You are not compelled to use recursion and write factorial like this:
(defun factorial (n)
(case n
((0 1) 1)
(otherwise (* n (factorial (- n 1))))))