Tutorial by Examples

Functions in Common Lisp are first class values. An anonymous function can be created by using lambda. For example, here is a function of 3 arguments which we then call using funcall CL-USER> (lambda (a b c) (+ a (* b c))) #<FUNCTION (LAMBDA (A B C)) {10034F484B}> CL-USER> (defvar *fo...
Any symbol in Common Lisp has a slot for a variable to be bound and a separate slot for a function to be bound. Note that the naming in this example is only for illustration. Global variables should not be named foo, but *foo*. The latter notation is a convention to make it clear that the variable ...
Common Lisp contains many higher order functions which are passed functions for arguments and call them. Perhaps the most fundamental are funcall and apply: CL-USER> (list 1 2 3) (1 2 3) CL-USER> (funcall #'list 1 2 3) (1 2 3) CL-USER> (funcall #'list 1 2 3 4 5) (1 2 3 4 5) CL-USER&g...
The reduce function can be used to sum the elements in a list. (reduce '+ '(1 2 3 4)) ;;=> 10 By default, reduce performs a left-associative reduction, meaning that the sum 10 is computed as (+ (+ (+ 1 2) 3) 4) The first two elements are summed first, and then that result (3) is added to...
Common Lisp already has a reverse function, but if it didn't, then it could be implemented easily using reduce. Given a list like (1 2 3) === (cons 1 (cons 2 (cons 3 '()))) the reversed list is (cons 3 (cons 2 (cons 1 '()))) === (3 2 1) That may not be an obvious use of reduce, but if we ha...
Functions remember the lexical scope they where defined in. Because of this, we can enclose a lambda in a let to define closures. (defvar *counter* (let ((count 0)) (lambda () (incf count)))) (funcall *counter*) ;; => 1 (funcall *counter*) ;; = 2 In the example above,...
A simple example: CL-USER> (defun make-apply-twice (fun) "return a new function that applies twice the function`fun' to its argument" (lambda (x) (funcall fun (funcall fun x)))) MAKE-APPLY-TWICE CL-USER> (funcall (make-apply-twice #'1+) 3) 5 ...

Page 1 of 1