Home
Main website
Display Sidebar
Hide Ads
Recent Changes
View Source:
QuickLispTutorial
Edit
PageHistory
Diff
Info
LikePages
!!! [LISP]’s very basics ''In the examples, any bold stuff is the result of running the code above it.'' This is a list: <verbatim> (apple orange banana) </verbatim> Lists can be nested: <verbatim> ((fruit (apple orange banana)) (colour (red green))) </verbatim> Lisp usually interprets lists as function calls: <pre> (+ 40 2) <b>42</b> </pre> Lisp usually interprets symbols (i.e. identifiers) as variable references: <pre> (* pi 2) <b>6.2831853071795862</b> </pre> A single-quote character "quotes" something, i.e. prevents Lisp from interpreting it. So the following is a list of symbols: <verbatim> '(elem1 elem2 elem3) </verbatim> <tt>let</tt> creates a list of variables that can be used in an expression: <verbatim> (let ((a 1) (b 2) (mylist '(a b))) expression) </verbatim> Hereafter, <tt>a</tt> will be 1, <tt>b</tt> = 2, <tt>mylist</tt> will contain the list <tt>'(a b)</tt>. <tt>setq</tt> changes the value of a variable: <verbatim> (setq mylist '(a b c)) </verbatim> The <tt>cons</tt> function makes a pair: <verbatim> (cons 'first 42) </verbatim> Cons pairs are usually used to make lists: the first element is the first element on the list; the second element is either a cons pair for the rest of the list or a <tt>nil</tt> to mark the end of the list. Consider the following list: <verbatim> '(1 2 3) </verbatim> This list is a shorthand for: <verbatim> (cons 1 (cons 2 (cons 3 nil))) </verbatim> <tt>car</tt> returns the first element of a list: <pre> (print (car mylist)) <b>a</b> </pre> <tt>cdr</tt> returns the rest of the list (ie all-but-first): <pre> (print (cdr mylist)) <b>(b c)</b> </pre> And that is basically [LISP]. !!! A somewhat realistic example The following example is an inefficient factorial function: <verbatim> (defun fact (x) ;a recursive function (if (> x 0) (* x (fact (- x 1))) 1)) </verbatim> (This stupid function has become the HelloWorld of functional ProgrammingLanguage~s for some reason.) !!! Further reading Look for the tutorial links on the [LISP] page. !!! Aside: where do these weird names come from? The names "<tt>car</tt>" and "<tt>cdr</tt>" came from the first machine that Lisp was written for: there were 2 registers and the commands "<tt>contents of address register</tt>" and "<tt>contents of decrement register</tt>". CommonLisp allows the more sensible names "<tt>first</tt>" and "<tt>rest</tt>".
One page links to
QuickLispTutorial
:
LISP