type “clisp” at command prompt to start interpreter (load “filename”) ; loads filename.lisp — if using an extension other than .lisp or .lsp, include extension (trace functionname) ; starts tracing function (untrace functionname) ; stops tracing function (quit) or (exit) to get out of clasp interpreter (if 3 2 0) ; returns 2 (if nil 2 0) ; returns 0 (defun cube (x) (* x x x)) (defun absval (x) (if (< x 0) (- x) x)) (defun pow (m n) (if (= n 0) 1 (* m (pow m (- n 1))))) (defun pow (m n) (if (< n 0) nil (if (= n 0) 1 (* m (pow m (- n 1)))))) (defun pow (m n) (cond ((< n 0) nil) ((= n 0) 1) (t (* m (pow m (- n 1)))))) (defun guess () (guess-helper (random 10))) (defun guess-helper (num) (let ((resp (read))) (princ "Guess an integer from 0 to 9:") (cond ((> resp num) (princ "Too high!")) (guess-helper (read) num))) ((< resp num) (princ "Too low!")) (guess-helper (read) num))) (t (princ "Lucky guess!"))))) ;will give you an unnamed function but no way to invoke it. (function (lambda (x) (* x x))) ; gives you the unnamed function and invokes it once with the parameter 3 (funcall (function (lambda (x) (* x x))) 3) ; Alternatively (funcall #'(lambda (x) (* x x)) 3) ;You can pass these "unnamed" functions as parameters, giving them a name in the process: (defun greater (f x y) (if (> (funcall f x) (funcall f y)) x y)) (greater #'(lambda (x) (if (< x 0) (- x) x)) 3 -5) ; returns -5 ; If passing a named function in as param (defun absval (x) (< x 0) (- x) x)) (greater 'absval -5 2) ; returns -5 ; add a list of integers (defun sumlist (x) (cond ((null x) 0) (t (+ (car x) (sumlist (cdr x)))))) ; (sumlist '(1 2 3)) returns 6 ; add 1 to each element in a list (defun inclist (x) (cond ((null x) ()) (t (cons (+ (car x) 1) (inclist (cdr x))))))) ; (inclist '(1 2 3)) returns (2 3 4) ;Function currying/lambda calculus ;We want to use a different technique that was introduced by the logician Schonfinkel ;and was made popular by Haskell Curry, hence is known as "currying". We can regard a ;function (x,y)->f(x,y) as a function mapping a value x to a function of y in which x is a ;fixed parameter: x->(y->f(x,y)). For example, we usually think of "addition" as a map of ;two numbers to their sum. In the curried picture, "addition" maps a number N to the ;function increase-by-N. Likewise, "multiplication" maps the number 2 to the duplication ;function, the number 3 to triplication, etc., and likewise for all other 2-arg functions. The ;generalization to 3-arg and higher functions is also possible. ; The function adder takes a parameter and returns a function that adds any number to x. (defun adder (x) #'(lambda (y) (+ x y))) ; The (adder 3) will return a function that adds 3 to any number. The funcall applies this new function to the parameter 5 - an 8 will be returned. (funcall (adder 3) 5) (setq adder3 (adder 3)) (funcall adder3 5)