; Examples showing atoms and the cons/2 function nil 1 (cons 1 nil) (cons nil nil) (cons 'a nil) (cons 'a 'b) (cons 1 (cons 2 (cons 3 nil))) ; (A B) '(A B) (cons 'C '(A B)) ; The following lets me re-read this file easily (defun again () (require "examples.lisp")) ; Shows how to define a function (defun consSelf (L) ; L is expected to be a list (cons L L) ) ; Sample uses of consSelf/1 (consSelf 1) (consSelf nil) (consSelf '(A B)) (cons 'a (cons '(b) (cons 'c nil))) (cons 'a (cons (cons 'b nil) (cons 'c nil))) ; Shows how to use a conditional (defun test1 (A) (cond ((eq A 1) "yes") (T "no") ) ) ; Sample uses of test1/1 (test1 1) (test1 '1) (test1 'a) (test1 2) (test1 (cons 1 nil)) ; The car/1 and cdr/1 functions (car '(a b)) (cdr '(a b)) (car '(1)) (cdr '(1)) (car '(a . b)) (cdr '(a . b)) ; Shows how to make a recursive function (defun lastElt (L) (cond ((null L) nil) ; L is empty: no last element ((null (cdr L)) (car L)) ; L is a one-element list (T (lastElt (cdr L))) ; recurse ) ) ; Sample uses of lastElt/1 (lastElt nil) ; (lastElt 1) (lastElt '(1)) (lastElt '(1 2 3)) (lastElt '(1 (2 2) 3)) (lastElt '(1 2 (3 3))) ; Arithmetic (defun incrementAll (L) (cond ((null L) nil) ; L is empty (T (cons (+ 1 (car L)) (incrementAll (cdr L)))) ) ) ; Tests of incrementAll/1 (incrementAll nil) ; (incrementAll 1) (incrementAll '(1)) (incrementAll '(1 3 5)) ; (incrementAll '(1 (3 3) 5)) ; Function with two parameters (defun incrementAll2 (L A) ; increment all elements of L by amount A (cond ((null L) nil) ; L is empty (T (cons (+ A (car L)) (incrementAll2 (cdr L) A))) ) ) ; Tests of incrementAll2/2 ; (incrementAll2 nil) (incrementAll2 nil 5) (incrementAll2 '(1) 5) (incrementAll2 '(1 3 5) 5) ; Example of recursion: list reversal (defun ReverseIt (L) (cond ((null L) nil) (T (append (ReverseIt (cdr L)) (cons (car L) nil))) ) ) (ReverseIt '(a b)) (ReverseIt '(a b (c d))) (ReverseIt '(a)) (ReverseIt '()) (ReverseIt '(a . b)) ; fails (ReverseIt 'a) ; fails (defun ReverseAll (L) (cond ((atom L) L) (T (append (ReverseAll (cdr L)) (cons (ReverseAll (car L)) nil))) ) ) (ReverseAll '(a b)) (ReverseAll '(a b ((c d) e) f)) (ReverseAll '(a)) (ReverseAll '()) (ReverseAll '(a . b)) ; fails (ReverseAll 'a) ; List manipulation: append (defun oppend (L1 L2) ; usually called APPEND and predefined (cond ((null L1) L2) (T (cons (car L1) (oppend (cdr L1) L2))))) ; List manipulation: mapcar (defun mapcor (F L) ; usually called MAPCAR and predefined (cond ((null L) nil) (t (cons (funcall F (car L)) (mapcar F (cdr L)))))) (mapcor (lambda (x) (* x x)) '(1 2 3 4)) (mapcor (lambda (x) (+ 1 x)) '(1 2 3 4)) ; lambda creates deep binding in Common Lisp (but not in Lisp 1.5) (defun selfCompose (F) (lambda (x) (funcall F (funcall F x)))) ; the use of F inside the lambda is nonlocal. When is it bound? (selfCompose (function car)) (funcall (selfCompose (function car)) '((a b) c)) ; it must be bound at elaboration time; by invocation time, car is gone.