Before you start learning Common Lisp

I've been learning Common Lisp and really enjoying it. The two crucial bits of advice to help you get started are:

  1. Use an editor that is aware of Lisp syntax
  2. Use the REPL - the Read Eval Print Loop
I'm using Emacs and the Carnegie Mellon University implementation (CMUCL) on FreeBSD. I start emacs and then type Meta-x run-lisp to start CMU Common Lisp. and Meta-x show-paren-mode to turn on parenthesis matching. Next I use Ctrl-x 3 to split the screen vertically, and Ctrl-x Ctrl-F learning/lisp/first-try.lisp to start editing my source file.

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) => 120
Well, 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))))))

Summary

  1. Your editor counts the parentheses for you and shows you whether they are in the right place by how it indents the code.
  2. The REPL lets you try out code fragments. Don't debug at the end, but test as you go.
  3. Compilation is used to speed up working code. Don't slow down development with an edit-compile-run cycle.
  4. You don't have to write your code in a functional style. Start from where you are.