To start Common Lisp REPL instance we simply call the ‘clisp’ programme
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | > clisp i i i i i i i ooooo o ooooooo ooooo ooooo I I I I I I I 8 8 8 8 8 o 8 8 I \ `+' / I 8 8 8 8 8 8 \ `-+-' / 8 8 8 ooooo 8oooo `-__|__-' 8 8 8 8 8 | 8 o 8 8 o 8 8 ------+------ ooooo 8oooooo ooo8ooo ooooo 8 Welcome to GNU CLISP 2.49.92 (2018-02-18) <http://clisp.org/> Copyright (c) Bruno Haible, Michael Stoll 1992-1993 Copyright (c) Bruno Haible, Marcus Daniels 1994-1997 Copyright (c) Bruno Haible, Pierpaolo Bernardi, Sam Steingold 1998 Copyright (c) Bruno Haible, Sam Steingold 1999-2000 Copyright (c) Sam Steingold, Bruno Haible 2001-2018 Type :h and hit Enter for context help. [1]> |
To get back to the command line we use the lisp function (quit) or (exit)
1 2 3 | [1]> (quit) Bye. > |
We have 3 ways to interact with lisp code, the most basic is to use the REPL CLI and just type in lisp code. This is great to experiment with but does not really scale beyond a few lines. We therefore typically store our code in files with the .lisp extension. We can then load a lisp file either via a command line parameter or via the (load ‘filename.lisp’) function
1 2 3 4 5 | clisp mycode.lisp ; or [1]> (load 'mycode.lisp') |
On Linux-based systems we can also turn the lisp code into a script. This involves creating a shell script and including the location of the clisp runtime as the first line. We then make the script executable with the ‘chmod +x’ command
1 2 3 4 5 6 7 8 9 | ; Create a script as follows, call it myscript.lisp #!/opt/homebrew/bin/clisp (pprint (+ 2 2)) ; The make it executable > chmod +x myscript.lisp ; Now we can execute it > ./myscript.lisp |
If during our REPL session we end up in the debugger then you can exit it back to the REPL CLI using CTRL-D
1 2 3 4 5 6 7 8 9 10 | > clisp ; Start Common Lisp [1]> (quit) ; Quit Common Lisp [1]> (/ 1 0) *** - /: division by zero The following restarts are available: ABORT :R1 Abort main loop Break 1 [2]> ; CTRL-D - Exit debugger [3]> |
In our lisp code, we can use comments to add documentation
1 2 3 4 5 6 7 8 9 10 11 | ;;; Single-line comments start with a semicolon; use four for file-level ;;; comments, three for section descriptions, two inside definitions, and one ;;; for single lines. ; Block Level Comments #| This is a block comment which can span multiple lines and #| they can be nested! |# |# |
Let’s start with the basics of atoms and s-expressions. The fundamental building blocks of Lisp are word objects or atoms. A string on atoms (words) for a list and lists can consist of atoms and lists, refered to as s-expressions ( the s stands for symbolic). This is the structure of your code in Lisp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | ;; Atoms, S-Expressions & Strings ;; An atom is a number or string or contiguous characters 10 ; an atom; it evaluates to itself :thing ; another atom; evaluating to the symbol :thing t ; another atom, denoting true f ; false ;; Bounding values to atoms using setf (setf answer 42) (setf result (* 2 7)) (set 'answer 43) (atom result) ; -> t, because result is an atom (atom '(1 2 3)). ; -> NIL ( or false ), because (1 2 3) is a list ;; An s-espression is an atom and/or other lists enclosed in () (+ 1 2 3 4) ; an s-expression '(4 :foo t) ; another s-expression ;; A string is sequence of characters enclosed in "" " I am a string" "a ba c d efg #$%^&!" |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | ;; A list is a sequence of atoms and/or other lists enclosed in parentheses. (+ 2 2) ;; Calls the + function with 2 parameters 2 and 2 (/ 4 2) ;; Calls divide with 2 params (+ (* 2 2) 3) ;; First evals 2 * 2 then adds it to 3 (* (+ 2 2) (- 4 1)) ;; 2 + 2 * 4 - 1 ;; Quoting lists (quote a) ;; => a 'a ;; => a '(a) ;; => (a) '(a b) ;; => (a b) '(a (b c) d) ;; (a (b c) d) ;; 'a is not the same as '(a) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | ;; Manipulating Lists (car ’(a b c)) ; => a First element of the list (cdr '(a b c)) ; => (b c) Remainer of the list (car ’(a)) ; => a First element of the list (cdr '(a)) ; => NILL Remainer of the list (car '()) ; NIL (cdr '()) ; NIL (c....r) ; Build up a series of car and cdr combinations ; starts with a c, ends with an r and for every ; a its a car and d its a cdr (caar '((a b)(x y))) ;; => A (caar '((a b c)(x y z))) ;; => A (cadar '((a b c)(x y z))) ;; => B (first ’(a b c)) ; => A Same as car (rest '(a b c)) ; => (B C) Same as cdr (last '(a b c)) ; => (C) // Creating lists (cons 'a NIL) ; => (A) (cons 'a '(b)) ; => (A B) (cons 'a '(b c d)) ; => (A B C d) (list 1) ; => (1) (list 'a) ; => (A) (list 'a 'b 'c) ; => (A B C) (append () '(A)) ; => (A) (append '(A) '(B C)) ; => (A B C) (length '(a bc d)) ; => 3 (reverse '(a b c)) ; => (C B A) (subst 'y 'm '(x m z)) ; => (X Y Z) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | ;; Data Types ;; Setq is used only for setting the values of symbols but setf can be used for anything. ;; Setf can be used for setting value of any data-type and not only symbols (setq myInt 123) ;; myInt == 123 (type-of myInt) ;; INTEGER (defvar myVal 42) ;; myVal == 42 (defvar myVal 43) ;; myVal == 42 - defvar does not change existing value ;; Type Specifiers array fixnum package simple-string atom float pathname simple-vector bignum function random-state single-float bit. hash-table ratio standard-char bit-vector integer rational stream character keyword readtable string [common] list sequence [string-char] compiled-function long-float short-float symbol complex nill signed-byte t cons null simple-array unsigned-byte double-float number simple-bit-vector vector |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | ;; Variables ;; Global Variables (defvar myval 100) ;; myval == 100 (defvar myval 200) ;; myval remains == 100 (setq myval 200) ;; myval == 200 (defvar name "Fred") (setq name "Ian") (type-of name) ;; => (SIMPLE-BASE-STRING 4) ;; Local Variables (let ((x 1))) ;; Defined inside a function (let ((x 1)(y 2)(z 3))) ;; Multiple variables ;; Constants (defconstant PI 3.141592) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | ;; Numbers fixnum ;; -215 - +214 bignum ;; Limited only by memory ratio ;; e.g. 2/3. The / function always returns this type float ;; Non integer numbers, e.g 2.456 complex ;; Complex, represented by c#, e.g #c( 1 2) ;; Number Functions +, -, *, / ;; Respective arithmetic operations sin, cos, tan, acos, asin, atan. ;; Respective trigonometric functions. sinh, cosh, tanh, acosh, asinh, atanh ;; Respective hyperbolic functions. exp ;; Exponentiation function. Calculates ex expt ;; Exponentiation function, takes base and power both. sqrt ;; It calculates the square root of a number. log ;; Logarithmic function. It one parameter is given, then it calculates its natural logarithm, otherwise the second parameter is used as base. conjugate ;; It calculates the complex conjugate of a number. In case of a real number, it returns the number itself. abs ;; It returns the absolute value (or magnitude) of a number. gcd ;; It calculates the greatest common divisor of the given numbers. lcm ;; It calculates the least common multiple of the given numbers. isqrt ;; It gives the greatest integer less than or equal to the exact square root of a given natural number. floor, ceiling, truncate, round ;; All these functions take two arguments as a number and returns the quotient; floor returns the largest integer that is not greater than ratio, ceiling chooses the smaller integer that is larger than ratio, truncate chooses the integer of the same sign as ratio with the largest absolute value that is less than absolute value of ratio, and round chooses an integer that is closest to ratio. ffloor, fceiling, ftruncate, ground ;; Does the same as above, but returns the quotient as a floating point number. mod, rem ;; Returns the remainder in a division operation. float ;; Converts a real number to a floating point number. rational, rationalize. ;; Converts a real number to rational number. numerator, denominator ;; Returns the respective parts of a rational number. realpart, imagpart ;; Returns the real and imaginary part of a complex number. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | ;; Characters #\a ; a #\b ; b : #\z ; z #\A ; A #\B ; B : #\Z ; Z #\1 ; 1 #\2 ; 2 : #\9 ; 9 ; Special Characters #\Backspace #\Tab #\Linefeed #\Page #\Return #\Rubout #\Space ; Character Comparison Case Sensitive Case-insensitive Description Functions. Functions char= char-equal Checks if the values of the operands are all equal or not, if yes then condition becomes true. char/= char-not-equal Checks if the values of the operands are all different or not, if values are not equal then condition becomes true. char< char-lessp Checks if the values of the operands are monotonically decreasing. char> char-greaterp Checks if the values of the operands are monotonically increasing. char<= char-not-greaterp. Checks if the value of any left operand is greater than or equal to the value of next right operand, if yes then condition becomes true. char>= char-not-lessp Checks if the value of any left operand is less than or equal to the value of its right operand, if yes then condition becomes true. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | ;; Arrays (make-array (dimensions ;; Size - number or list :element-type ;; Element type, default T (any) :initial-element ;; Initial element values :initial-contents ;; Initial content as object. :adjustable ;; T - resizable, NIL - not :fill-pointer ;; Number of elements in list :displaced-to :displaced-index-offset) (setf my-array (make-array '(10))) ;; Create an array of 10 elements (aref my-array 7) ;; Eigth element (setf (aref my-array 0) 25) ;; Set the first element (setf x (make-array '(3 3) )) ;; 2D Array (setf x (make-array '(3 3 3) )) ;; 3D Array |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | ;; Strings "This is a string" ;; Surrounded by "'s "This is a \"quoted\" string" ;; Adding "'s to a string (length "12345) ;; => 5 ;; String Comparison Functions Case Sensitive Case-insensitive Description Functions Functions string= string-equal Checks if the values of the operands are all equal or not, if yes then condition becomes true. string/= string-not-equal Checks if the values of the operands are all different or not, if values are not equal then condition becomes true. string< string-lessp Checks if the values of the operands are monotonically decreasing. string> string-greaterp Checks if the values of the operands are monotonically increasing. string<= string-not-greaterp Checks if the value of any left operand is greater than or equal to the value of next right operand, if yes then condition becomes true. string>= string-not-lessp Checks if the value of any left operand is less than or equal to the value of its right operand, if yes then condition becomes true. ;; Case Control string-upcase ;; Converts the string to upper case string-downcase ;; Converts the string to lower case string-capitalize ;; Capitalizes each word in the string ;; Trimming string-trim ;; It takes a string of character(s) as first argument and a string as the second argument and returns a substring where all characters that are in the first argument are removed off the argument string. String-left-trim ;; It takes a string of character(s) as first argument and a string as the second argument and returns a substring where all characters that are in the first argument are removed off the beginning of the argument string. String-right-trim ;; It takes a string character(s) as first argument and a string as the second argument and returns a substring where all characters that are in the first argument are removed off the end of the argument string. ;; String manipulating subseq ;; Substring, start, end ( or end of line ) char ;; Individual charatcers sort ;; Sort a string merge ;; Merge 2 sequences reverse ;; Reverse a string concatenate ;; Concatenate 2 strings |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | ;; Sequences make-sequence sqtype sqsize &key :initial-element (write (make-sequence '(vector float) 10 :initial-element 1.0)) ;; => #(1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0) ;; Argument Meanings :test ; It is a two-argument function used to compare item (or value extracted by :key function) to element. EQL :key ; One-argument function to extract key value from actual sequence element. NIL means use element as is. NIL :start ; Starting index (inclusive) of subsequence. 0 :end ; Ending index (exclusive) of subsequence. NIL indicates end of sequence. NIL :from-end. ; If true, the sequence will be traversed in reverse order, from end to start. NIL :count ; Number indicating the number of elements to remove or substitute or NIL to indicate all (REMOVE and SUBSTITUTE only). NIL ;; Sequence Functions elt ; It allows access to individual elements through an integer index. length ; It returns the length of a sequence. subseq ; It returns a sub-sequence by extracting the subsequence starting at a particular index and continuing to a particular ending index or the end of the sequence. copy-seq ; It returns a sequence that contains the same elements as its argument. fill ; It is used to set multiple elements of a sequence to a single value. replace ; It takes two sequences and the first argument sequence is destructively modified by copying successive elements into it from the second argument sequence. count ; It takes an item and a sequence and returns the number of times the item appears in the sequence. reverse ; It returns a sequence contains the same elements of the argument but in reverse order. nreverse ; It returns the same sequence containing the same elements as sequence but in reverse order. concatenate ; It creates a new sequence containing the concatenation of any number of sequences. position ; It takes an item and a sequence and returns the index of the item in the sequence or nil. find. ; It takes an item and a sequence. It finds the item in the sequence and returns it, if not found then it returns nil. sort ; It takes a sequence and a two-argument predicate and returns a sorted version of the sequence. merge ; It takes two sequences and a predicate and returns a sequence produced by merging the two sequences, according to the predicate. map ; It takes an n-argument function and n sequences and returns a new sequence containing the result of applying the function to subsequent elements of the sequences. some ; It takes a predicate as an argument and iterates over the argument sequence, and returns the first non-NIL value returned by the predicate or returns false if the predicate is never satisfied. every ; It takes a predicate as an argument and iterate over the argument sequence, it terminates, returning false, as soon as the predicate fails. If the predicate is always satisfied, it returns true. notany ; It takes a predicate as an argument and iterate over the argument sequence, and returns false as soon as the predicate is satisfied or true if it never is. notevery ; It takes a predicate as an argument and iterate over the argument sequence, and returns true as soon as the predicate fails or false if the predicate is always satisfied. reduce ; It maps over a single sequence, applying a two-argument function first to the first two elements of the sequence and then to the value returned by the function and subsequent elements of the sequence. search ; It searches a sequence to locate one or more elements satisfying some test. remove ; It takes an item and a sequence and returns the sequence with instances of item removed. delete ; This also takes an item and a sequence and returns a sequence of the same kind as the argument sequence that has the same elements except the item. substitute ; It takes a new item, an existing item, and a sequence and returns a sequence with instances of the existing item replaced with the new item. nsubstitute ; It takes a new item, an existing item, and a sequence and returns the same sequence with instances of the existing item replaced with the new item. mismatch ; It takes two sequences and returns the index of the first pair of mismatched elements. ;; Mapping a Sequence (write (map 'vector #'* #(2 3 4 5) #(3 5 4 8))) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | ;; More on lists ;; cons record - Simple linked list record to uis used to construct lists ;; Consists of 2 elemements ( car . cdr ) ;; car - first element in the list ;; cdr - remaining elements of the list (cons 1 2) ;; (1 . 2) (cons 'a 'b) ;; (A . B) (cons 1 nil) ;; (1) (cons 1 (cons 2 nil)) ;; (1 2) (cons 1 (cons 2 (cons 3 nil))) ;; (1 2 3) (cons 'a (cons 'b (cons 'c nil))). ;; (A B C) ;; Paramterised Lists (list :x 1 :y 2 :z 3) (setq mylist (list :x 1 :y 2 :z 3)). ;; => (:X 1 :Y 2 :Z 3) (getf mylist :x) ;; => 1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | ;; Symbols ;; Symbols represent data objects ;; Symbols are also data objects themselves ;; Symbols can have properties (setf (get 'programmer 'name) 'keith) (setf (get 'programmer 'age) 55) (get 'programmer 'name) ;; KEITH (get 'programmer 'age) ;; 53 (symbol-plist 'programmer) ;; (AGE 53 NAME KEITH) (remprop 'programmer 'age) ;; (NAME KEITH) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | ;; Vectors ;; 1 dimensional array (setf v1 (vector 1 2 3 4 5)) ;; #(1 2 3 4 5) (setf v2 #(a b c d e)) ;; #(A B C D E) (setf v3 (vector 'p 'q 'r 's 't)) ;; #(P Q R S T) (setq a (make-array 5 :initial-element 0)) (setq b (make-array 5 :initial-element 2)) make-array length fill-pointer vector-push vector-pop |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | ;; Sets ;; Immutable, non duplicating collection of data items (setf myset ()) ;; Creates an empty set (adjoin 1 myset) ;; myset still () as adjoin returns new set (setf myset (adjoin 1 myset)) ;; (1) (setf myset (adjoin 2 myset)) ;; (2 1) (setf myset (adjoin 3 myset)) ;; (3 2 1) (setf myset (adjoin 3 myset)) ;; (3 2 1). - Non duplicating ;; Membership member item list &key :test :test-not :key member-if predicate list &key :key member-if-not predicate list &key :key (member 1 myset) ;; (1) - tail of list from where item found (member 5 myset) ;; NIL (member 2 myset) ;; (2 1) - tail of list from 2 (member-if #'evenp myset) ;; (2 1) - tail from first even ;; Union union list1 list2 &key :test :test-not :key nunion list1 list2 &key :test :test-not :key ;; Intersection intersection list1 list2 &key :test :test-not :key nintersection list1 list2 &key :test :test-not :key ;; Difference set-difference list1 list2 &key :test :test-not :key nset-difference list1 list2 &key :test :test-not :key |
1 2 3 4 5 | ;; Trees https://www.tutorialspoint.com/lisp/lisp_tree.htm https://www2.cs.sfu.ca/CourseCentral/310/pwfong/Lisp/3/tutorial3.html |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | ;; Hashtables (setq programmers (make-hash-table)) ;; => #S(HASH-TABLE :TEST FASTHASH-EQL) (setf (gethash 'guy programmers) '(Lisp)) (setf (gethash 'brian programmers) '(C)) (setf (gethash 'bjorne programmers) '(C++)) programmers ;; #S(HASH-TABLE :TEST FASTHASH-EQL (BJORNE . (C++)) (BRIAN . (C)) (GUY . (LISP))) (gethash 'guy programmers) ;; (LISP) (gethash 'bjorne programmers) ;; (C++) (gethash 'keith programmers) ;; NIL (maphash #'(lambda (k v) (format t "~a => ~a~%" k v)) empList) BJORNE => (C++) BRIAN => (C) GUY => (LISP) NIL (remhash 'bjorne programmers) programmers ;; #S(HASH-TABLE :TEST FASTHASH-EQL (BRIAN . (C)) (GUY . (LISP))) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | ;; Operators (setq x 40) (setq y 2) ;; Arithmetic Operators (+ x y) ;; Addition (- x y) ;; Subtraction (* x y) ;; Multiplication (/ x y) ;; Division (mod x y) ;; Modulus Operator of integer division (rem x y) ;; Remainder of integer division (incf x) ;; Increment x by 1 (incf x 2) ;; Increment x by 2 (decf x) ;; Decrement y by 1 (decf x 2) ;; Decrement y by 2 ;; Logical Operators (= x y) (/= x y) (> x y) (>= x y) (< x y) (<= x y) (min x y) (min 1 2 4) (max x y) (max 1 2 4) ;; Boolean Operators (and x y) (or x y) (not x) ;; Bitwise Operators (logand x y) (logor x y) (logxor x y) (lognor x y) (logeqv x y) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | ;; Predicates atom ;; returns t if the argument is an atom or nil if otherwise. equal ;; returns t if arguments are structurally equal or nil otherwise. eq ;; returns t if arguments are same identical objects, sharing the same memory location or nil otherwise. eql ;; returns t if the arguments are eq, or if they are numbers of the same type with the same value, or if they are character objects that represent the same character, or nil otherwise. evenp ;; returns t if the argument is even number or nil if otherwise. oddp ;; returns t if the argument is odd number or nil if otherwise. zerop ;; returns t if the argument is zero or nil if otherwise. null ;; returns t if the argument evaluates to nil, otherwise it returns nil. listp ;; returns t if the argument evaluates to a list otherwise it returns nil. greaterp ;; returns t if either there is a single argument or the arguments are successively larger from left to right, or nil if otherwise. lessp ;; returns t if either there is a single argument or the arguments are successively smaller from left to right, or nil if otherwise. numberp ;; returns t if the argument is a number or nil if otherwise. symbolp ;; returns t if the argument is a symbol otherwise it returns nil. integerp ;; returns t if the argument is an integer otherwise it returns nil. rational ;; returns t if the argument is rational number, either a ratio or a number, otherwise it returns nil. floatp ;; returns t if the argument is a floating point number otherwise it returns nil. realp ;; returns t if the argument is a real number otherwise it returns nil. complexp ;; returns t if the argument is a complex number otherwise it returns nil. characterp ;; returns t if the argument is a character otherwise it returns nil. stringp ;; returns t if the argument is a string object otherwise it returns nil. arrayp ;; returns t if the argument is an array object otherwise it returns nil. packagep ;; returns t if the argument is a package otherwise it returns nil. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | ;; Decisions ;; cond (setf a 10) (cond ((= a 10)(print "eq"))) ;; if statement (cond ((= a 10)(print "eq")) ;; if ((> a 10)(print "gt"))) ;; elif (cond ((= a 10)(print "eq")) ;; if ((> a 10)(print "gt")) ;; elif (t (print "lt"))) ;; else ;; if (setf a 10) (if (= a 10)(print "eq")) ;; if (if (= a 10)(print "eq") ;; if (print "neq")) ;; else ;; when (setf a 10) (when (= a 10)(print "eq")) ;; case (setq day 4) (case day (1 (format t "~% Monday")) (2 (format t "~% Tuesday")) (3 (format t "~% Wednesday")) (4 (format t "~% Thursday")) (5 (format t "~% Friday")) (6 (format t "~% Saturday")) (7 (format t "~% Sunday"))) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | ;; Loops ;; loop (setq a 10) (loop (setq a (+ a 1)) (print a) (when (> a 20) (return a)) )) ;; loop-for (loop for a from 10 to 20 do (print a) ) (loop for x in '(1 2 3 4 5) do (print x) ) ;; do (do ((x 0 (+ x 1)) ;; X = 0, X = X +1 ) ((eq x 5) x) ;; Loop until x == 5, then return x (print x) ) (do ((x 0 (+ x 1)) ;; x = 0 (y 10 (- y 1)) ;; y = 10 ) ((eq x y) x) ;; Meet in the middle and return x (print x) ) ;; dotimes (dotimes (n 11) (print n) (prin1 (* n n)) ) ;; dolist (dolist (element '(0 1 2 3 4 5 6 7 8 9)) (print element)) ;; blocks (block block-name1( (block block-name2( (return-from block-name2 t) )) )) |
A macro is defined with the pre-processor directive. Macros are pre-processed which means that all the macros would be processed before your program compiles.
1 2 3 4 5 6 7 8 9 | ;; Macros (defmacro macro-name (parameter-list)) "Optional documentation string." body-form (defmacro doubleIt(x) (* 2 x)) (doubleit 2) 4 |
However, functions are not preprocessed but compiled
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | ;; Functions (defun name (parameter-list) "Optional documentation string." body) (defun add2 (x y) (+ x y)) (add2 1 2) ;; 3 ;; Optional Parameters (defun printall (a b &optional c d) (print (list a b c d))) (printall 1) ;; Error, too few parameters (printall 1 2) ;; 1 2 NIL NIL (printall 1 2 3) ;; 1 2 3 NIL (printall 1 2 3 4) ;; 1 2 3 4 (printall 1 2 3 4 5) ;; Error, too many arguments ;; Rest Parameters (defun printall (a &rest remaining) (print (list a remaining))) (printall 1) ;; (1 NIL) (printall 1 2) ;; (1 2) (printall 1 2 3 4 5) ;; (1 2 3 4 5) (defun printall (a &rest remaining) (print (cons a remaining))) (printall 1) ;; (1) (printall 1 2) ;; (1 2) (printall 1 2 3 4 5) ;; (1 2 3 4 5) ;; Keyword Parameters (defun printall (&key p1 p2 p3 p4) (print (list p1 p2 p3 p4))) (printall :p1 1) ;; (1 NIL NIL NIL) (printall :p1 1 :p2 3 :p3 5) ;; (1 3 5 NIL) ;; Returning Values (defun addTwo(x y) (+ x y)) ;; Returns last expression evaluated (defun addTwo(x y) (* x y) ;; Ignore in terms of return (+ x y)) ;; Returns last expression evaluated (defun add (a b) (return-from add (* a b)) ;; Return immediately, no further eval (+ a b)) ;; Lambda Functions ((lambda (x) (+ x 1)) 13) ;; => 14 (setq f (lambda (x) (+ x x))) (funcall f 2) ;; => 4 ;; Mapping Functions (write (mapcar '1+ '(1 2 3))) ;; Map the function 1+ to each value ;; => (2 3 4) mapc mapcar mapcan mapcan mapl maplist mapcon |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | ;; Input / Output ;; Input read & optional input-stream eof-error-p eof-value recursive-p read-preserving-whitespace & optional in-stream eof-error-p eof-value recursive-p read-line & optional input-stream eof-error-p eof-value recursive-p read-char & optional input-stream eof-error-p eof-value recursive-p read-byte binary-input-stream & optional eof-error-p eof-value read-from-string string & optional eof-error-p eof-value & key :start :end :preserve-whitespace unread-char character & optional input-stream peek-char & optional peek-type input-stream eof-error-p eof-value recursive-p listen & optional input-stream read-char-no-hang & optional input-stream eof-error-p eof-value recursive-p clear-input & optional input-stream parse-integer string & key :start :end :radix :junk-allowed (write (read)) ;; Write what you read ;; Create a string stream made up of ABCD and read from the stream (with-input-from-string (stream "ABCD") (print(read-line stream))) ;; Output write object & key :stream :escape :radix :base :circle :pretty :level :length :case :gensym :array write object & key :stream :escape :radix :base :circle :pretty :level :length :case :gensym :array :readably :right-margin :miser-width :lines :pprint-dispatch prin1 object & optional output-stream print object & optional output-stream pprint object & optional output-stream princ object & optional output-stream prin1 returns the object as its value. print prints the object with a preceding newline and followed by a space. It returns object. pprint is just like print except that the trailing space is omitted. prin1-to-string object princ-to-string object write-to-string object & key :escape :radix :base :circle :pretty :level :length :case :gensym :array write-to-string object & key :escape :radix :base :circle :pretty :level :length :case :gensym :array :readably :right-margin :miser-width :lines :pprint-dispatch write-char character & optional output-stream write-string string & optional output-stream & key :start :end write-line string & optional output-stream & key :start :end write-byte integer binary-output-stream terpri & optional output-stream fresh-line & optional output-stream finish-output & optional output-stream force-output & optional output-stream clear-output & optional output-stream ;; Formatted output format destination control-string &rest arguments (format t "Radius: = ~F~% Area = ~F" radius area) ~A ;; Is followed by ASCII arguments. ~S ;; Is followed by S-expressions. ~D ;; For decimal arguments. ~B ;; For binary arguments. ~O ;; For octal arguments. ~X ;; For hexadecimal arguments. ~C ;; For character arguments. ~F ;; For Fixed-format floating-point arguments. ~E ;; Exponential floating-point arguments. ~$ ;; Dollar and floating point arguments. ~% ;; A new line is printed. ~* ;; Next argument is ignored. ~? ;; Indirection. The next argument must be a string, and the one after it a list. |
1 2 3 4 5 6 7 8 9 10 | ;; File I/O open filename &key :direction :element-type :if-exists :if-does-not-exist :external-format with-open-file (stream filename {options}*) {declaration}* {form}* close |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | ;; Packages ;; Predefined ommon-lisp ;; it contains symbols for all the functions and variables defined. common-lisp-user ;; it uses the common-lisp package and all other packages with editing and debugging tools; it is called cl-user in short make-package package-name &key :nicknames :use in-package package-name &key :nicknames :use in-package name find-package name rename-package package new-name &optional new-nicknames list-all-packages delete-package package ;; Creation (defpackage :package-name (:use :common-lisp ...) (:export :symbol1 :symbol2 ...) ) ;; Or make-package package-name &key :nicknames :use ;; Usage (make-package :pack1) (make-package :pack2) (in-package pack1) (defun hello () (write-line "Hello! This is Package 1") ) (in-package dick) (defun hello () (write-line "Hello! This is Package 2") ) (in-package pack1) (hello) ;; => Hello! This is Package 1 (in-package pack2) (hello) ;; => Hello! This is Package 2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | ;; Error Handling (define-condition condition-name (error) ((text :initarg :text :reader text)) ) ;; Signalling a condition error format-string &rest args cerror continue-format-string error-format-string &rest args warn format-string &rest args break &optional format-string &rest args ;; Handle a condition (handler-case expression error-clause*) ;; Restart the process (handler-bind (binding*) form*) (invoke-restart "Message") |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | ;; Structures (defstruct programmer firstname lastname language) ;; Creates a structure programmer ;; programmer is now a data type ;; Creates 3 accessor methods ;; programmer-firstname ;; programmer-lastname ;; programmer-language ;; Creates 1 predicate to check for type ;; programmer-p ;; Creates a constructor ;; make-programmer ;; Creates a copy function ;; copy-programmer (setf p1 (make-programmer :firstname "Guy" :lastname "Steele" :language "Lisp")) (write (programmer-firstname p1)) (programmer-p p1) (setf p2 (copy-programmer p1)) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | ;; CLOS ;; Common Lisp Object System (defclass class-name (superclass-name*) (slot-description*) class-option*)) ;; Slot Options :accessor function-name :initform expression :initarg symbol ;; Construction (defclass Box () ((length :accessor length) (breadth :accessor breadth) (height :accessor height) ) ) ;; or (defclass Box () ((length :reader get-length :writer set-length) (breadth :reader get-breadth :writer set-breadth) (height :reader get-height :writer set-height) ) ) ;; Creation (make-instance class {initarg value}*) (setf item (make-instance 'box)) (setf (box-length item) 10) (setf (box-breadth item) 10) (setf (box-height item) 5) ;; Class methods (defmethod volume ((object box)) (* (box-length object) (box-breadth object)(box-height object)) ) ;; Inheritance (defclass wooden-box (box) ((price :accessor box-price))) |
1 2 3 4 5 6 7 8 9 10 11 12 | ;; Useful Lisp Functions (BYE) ;; Quit REPL (quit) ;; Quit REPL LOAD ;; (LOAD "fn.lsp") HELP ;; (help 'car) TRACE ;; (trace aaa bbb) Causes all calls to aaa and bbb to be traced PRIN1 ;; prints its argument, without a newline. PRINT ;; prints its argument and then a newline. READ ;; reads and returns an S-expression. TERPRI ;; Print a new line WRITE ;; Write to console |
Common lisp has a fixed number of special forms ( currently 25 )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | ;; Common Lisp Special Forms block ;; catch ;; eval-when ;; felt ;; function ;; go ;; if ;; labels ;; let ;; let* ;; load-time-value ;; locally ;; macrolet ;; multiple-value-call ;; multiple-value-prog1 ;; progn ;; progv ;; quote ;; return-from ;; setq ;; symbol-macrolet ;; tagbody ;; the ;; throw ;; unwind-protect ;; |