# Common Lisp/First steps/Beginner tutorial

Start up your Lisp implementation. You will most likely see a window with a prompt waiting for your input. This prompt is called a REPL for Read-Evaluate-Print Loop. At this point, Lisp is waiting for the expression to read and then evaluate, which in simple words means to calculate its result.
Type "2" and press Return (or Enter)
The lisp interpreter looks at 2 and evaluates it. It recognizes it as a number, and applies the rule that numbers evaluate to themselves, so the answer is 2.

## Addition

Type "(+ 2 2)" and press Return
The computer sees the opening parenthesis and realizes it is being given a list. When it reaches the closing parenthesis it is able to work out that it has seen a list of three elements. The first is the + sign, so it knows to add together the values of the remaining items on the list. So it evaluates them, the number 2 having the value 2 as before. Answer: 4

### Things to do wrong

* Forget to type return. You always have to type return at the end to tell the computer that you have finished your turn and it's its turn to go.
* Leave out the first space:
* Think it's a typo and try:
* Think it's a typo and do the infix thing
* Put in spaces

### Explanation

Instead of writing 1+20+300+4000+50000, one writes the plus sign as the first item of a list that can be as long as you wish.
The list appears to be laid out like one might lay out a shopping list: (potatoes carrots onions bread milk) with no concession to the idea that + is part of arithmetic and a bit special. Be careful though. The first location on the list is special, and + has to come first.

## Multiplication

For multiplication we use the ‘*’ function.
Can you use a list as long as you want? Yes.
In fact, you can use lists as short as you want.
Why? There are depths here that must be deferred until later.

## Subtraction

Subtraction is as clunky in Lisp as in any other language.
In other words,
is the same as

## Division

Division contains a surprise.
Lisp does fractions
This is potentially confusing:
If you try (/ 2 3) you get 2/3 which is probably an unpleasant surprise, if you were expecting 0.6666667. If you had tried (/ 8 12) you would also have got 2/3, which might have been a pleasant surprise. If you don't want a fraction, you can always say
or
Division works the same way as subtraction with
being the same as
This works OK in practice. A calculation such as 6×5×4/(3×2×1) gets translated to the following piece of Lisp:

## Binding

Binding is the act of specifying a place holder for a value. The concept is analogous to that of a local variable in C or Java. You often want to do this because it is cumbersome to write out long expressions multiple times, or if a computation needs to be done in small parts where a binding needs to be updated at various times during execution. The main way to create bindings is via the “special form” LET.
Here, 5-SQUARED and 10-SQUARED are place holders ("local variables") for the results of the calculation (* 5 5) and (* 10 10), respectively. It is good to note at this time that there are very few rules regarding what can be used as a place holder. These place holders are called symbols and it can have a name that includes most any characters with the exception of quotes, open or close parenthesis, colons, backslashes, or vertical bars (‘|’). These all have special syntactical meaning in Common Lisp. It is good to note that all of these things actually can be in the name of a symbol but they require special escaping.
Bindings have a limited scope. Once the LET form closes, the binding is invalidated. This means that this is an error, because a is referred to outside of the enclosing LET form.
It is interesting to note the behavior if you bind a symbol that has already been bound. Once the inner binding is released, the outer one is in effect again.
The story gets a bit more complex, there are two types of way to make bindings in Common Lisp, lexical, which we have just seen, and dynamic. For our purposes at this point, dynamic bindings are not much different from lexical bindings, but they are made in a different way and do not have the same finite extent of the LET form. We can use DEFVAR and DEFPARAMETER to make dynamic bindings. These can hold a value in between inputs.

## Variables

In Lisp, variables have some extra features, and are called symbols. A variable is a box containing a value. A symbol is a somewhat larger box, with its name written on the side. A symbol has two values, a general purpose value, and a function value used instead in particular circumstances. You can use the symbol as a thing in itself, without regard to its value.

### setf

We start by setting a symbol's general purpose value. There are several commands for setting the values of symbols, set, setq, setf, psetq, psetf. One can get a long way with just setf so we start with that one
This sets the general purpose value of the symbol MY-FIRST-SYMBOL to 57, and returns 57. Now we can type
and
Well, plainly this has performed the calculation, and returned the answer, but what did the general purpose value of our second-symbol get set to? Have we used it to record the calculation we requested, (+ 20 3), or the answer that the computer calculated?
If we want to record the calculation for future reference we must "quote" it. Think of the computer as a horse and the quote as a bridle, reining it in, stopping it from rushing on to evaluate things before you want it to.
Now
the general purpose value of our third symbol contains a calculation, which the computer is champing at the bit to execute.

### eval

If quote pulls on the reins, how do we get started again? The answer: eval.
It is controversial to use quote in the first lesson because it is seldom typed in explicitly. One types
Notice that this is a very special abbreviation. Not only are the five letters of quote shortened to the single character ', but the brackets are also omitted. It should be noted that when we use a lisp interpreter, we are essentially in an infinite READ-EVAL-PRINT loop. Thus, we are really using eval all the time.

### list

We have set three symbols so far and are perhaps in danger of forgetting what they contain. The function list builds a list, e.g.
so lets build a list of the values of our three symbols
There are two potential confusions here. One of them is figuring out which value is which. Perhaps we should turn off evaluation using quote:
The second and more serious confusion arise from comparing
and
It looks as though list is somehow deciding whether or not to evaluate its arguments, refraining in the first instance and rushing ahead in the second.
With quote and eval we can investigate this. Let us evaluate 1 zero times, once, twice, and three times
Compare this to evaluation third, zero, one, two, and three times.
Numbers are not symbols. There is no box containing two values. They just are, and they evaluate to themselves. Since numbers are not symbols,
does not work. You can get a feel for what is going on by typing
Now my-symbol-1 evaluates to itself. It shrugs off evaluation just as numbers do.
I'm going to belabor this point. I have a reason. The metaphor of a variable as a box that contains things is a good one. Much of the time the metaphor works well. You keep something in the box for a while. Then you throw the contents away and use the box to keep something else instead. Unfortunately the metaphor is fundamentally flawed. Both the box and its contents are immaterial. Consider
Has the list describing a simple calculation been put in the box 4th?
Yes.
Has it been taken out of third?
No.
Has it been copied? No. You make a copy like this:
Has it been moved? No. To the extent that the metaphor of motion works at all, you move things like this
There is a command (shiftf 6th 5th nil) which writes nil to 5th after moving the contents to 6th, but it returns the old contents of 6th, so it cannot be used on shiny new variables with no contents.
If it has not been copied and it has not been moved, what has happened? Something special to the immaterial world of tangled boxes, which we will not explore today.
For a striking example do
now
Now for the key test. What happens with (+ 1 (* 2 3)) and (+ 1 '(* 2 3))? The second of these is easy to understand. We have used quote to prevent evaluation, so (* 2 3) is a list of three items, giving instructions for an arithmetical calculation to be carried out at some later time. It is not the result of the calculation it describes and is not a number. Sure enough:
By contrast
appears cleverer than it really is. It looks like the interpreter looks at its arguments and decides which ones to evaluate. For example it looks as though
is realizing that it needs to evaluate argument 2 and 3 while leaving 1 and 4 alone.
In fact
only looks like it is doing what you think. It is evaluating 2 and 3, getting 2 and 3 as the results of the two evaluations, then multiplying the two results to get six.
When the interpreter evaluates (+ 1 (* 2 3)) it evaluates 1 and (* 2 3). 1 evaluates to 1, (* 2 3) evaluates to 6. Then it adds them to get 7.
There is something worth pondering here. Get a cheap, old, pocket calculator out of a drawer and try 1 + 2 x 3 Typically, when you press x, the calculator, lacking an extra register to hold pending results, carries out the addition of the one and the two. One ends up calculating 3 x 3 and getting 9, rather than 7. Modern calculators follow the standard rules of precedence, and defer performing the addition until after they have multiplied 2 by 3, eventually arriving at 7, as desired.
Computer languages have many more operations than addition and multiplication and often have elaborate systems of precedence controlling which operations are carried out first. Lisp has no such subtlety. One either writes
(1+2)x3 as
or one writes
1+(2x3) as
there is no way to preserve the ambiguity of 1+2x3
This turns out to be for the best in practice.
Obscure note: You could try (+ 1 * 2 3). At the top level, * is used for recalling the result of the previous command. If that was a number it will give the wrong answer. If that was not a number the interpreter will signal an error. Within a program, (+ 1 * 2 3) will generate an error message saying that * has no value. More on this later.
Let us return to third. Remember that we set our third symbol to a list of three items. We can see the whole list by typing third
Lisp has functions for extracting items from a list. First gets the first item
The function second gets the second item on the list.
If we would prefer multiplication we can change the symbol at the start of the list
We can change the second item
and, mysteriously, we can do the same with the third item
How does this work? Remember what I said earlier "A symbol has two values, a general purpose value, and a function value used instead in particular circumstances."
The particular circumstances are when eval is evaluating the first symbol in a list. The function that eval applies, to the result of evaluating the other items in the list, is the function value of the symbol, not the general purpose value of the symbol.

### symbol-function, symbol-value

To make this clear, use symbol-function and symbol-value
This is very confusing. The interpreter stores the last command executed as the general purpose value of the symbol +, so (symbol-value '+) depends on what you did last. In side a program (symbol-val '+) will do something like
just the same as

### boundp

All these error messages are quite annoying. Is there any way to avoid them? Yes. boundp checks whether there is a general purpose value, and fboundp checks whether there is a function value,
T is used for true
NIL is used for false, rather than F
Introductions to Lisp usually keep quiet about symbol-function. I understand why. Now that I have told you about it, you are equipped to wreck havoc, and undertake all sorts of devious mischief.
For example
and
give access to the functions that add and multiply.
Lets save them for later
Notice that you can set as many symbols as you want with a single setf.
Notice also that I have put these functions in the general purpose values of the symbols
Notice that
works as well. I'm using symbol-value to make the parallel to symbol-function more apparent.
You can store functions in general purpose value of a symbol. It really is the general purpose the value of the symbol, not the data value of the symbol.
doesn't work. When eval tries to evaluate a list that starts with a symbol, it looks for the function value of the symbol, and signals an error if it cannot find one.
works. So does
and
and
It is worth remembering that apply subsumes funcall, i.e. all of these work
Back to mischief
He he, you've got it, I'm swapping round + and *
I'd better put them back
phew, that's better.
symbol-function is heavily used. So not only is there an easier way of writing it, (function +) instead of (symbol-function (quote +)), but the simplified way even has its own abbreviation #'+. Err, that's not quite right, but it will have to do for now.