Dana Vrajitoru
C311 Programming Languages

Lisp Variables, Functions, Conditional

Values, Variables

Defining Variables

Expressions

Evaluation in Lisp

Defining Functions

(defun name (arg1 arg2 ...)
    "function description"
    sequence of expressions)
The function description is optional and specific to elisp.
(defun square (x)
  (* x x))          ; => square
(square 5)          ; => 25

Conditional

(if (condition)
    expression if true
    expressions if false)
Alternatives in elisp for the conditional:
(when (condition) expressions)
(unless (condition) expressions)
(defun max (x y)
  (if (> x y) x y))

Example - Factorial
factorial(n) = n * factorial(n-1)

(defun factorial (n)
  "Computes the factorial of a number"
  (if (<= n 1) 1
        (* n (factorial (- n 1)))))

(factorial 5)  ; 120

List Length

Example - sumlist

(defun sumlist (L)
  "Returns the sum of the elements of the list." 
  (if (not L) 
      0
    (+ (car L) 
       (sumlist (cdr L)))))

(sumlist '(8 2 5 1))  ; 16

Function Example

(defun last (L)
  "The last element in a list"
  (if (not L)
      nil
    (if (not (cdr L))
        (car L)
      (last (cdr L)))))
(last ())         ;->  nil
(last '(1))       ;->  1
(last '(1 2 3 4)) ;->  4
Alternative version, considering that when the list is empty both the car and the cdr return nil:
(defun last (L)
  "The last element in a list"
  (if (not (cdr L))
      (car L)
    (last (cdr L))))

Grouping Expressions

Complex Conditional

(cond (c1 exp1) (c2 exp2)... )

Example

(progn
  (setq n (% (random) 100))
  (cond
   ((< n 0)
    (princ "you are not born yet")
    (princ "what are you doing here?"))
   ((< n 15) (princ "you are in junior high"))
   ((< n 16) (princ "you'll learn to drive soon"))
   ((< n 21) (princ "you shouldn't be drinking"))
   (t (princ "believe it or not, you're an adult now")))
)

Examples

(defun last (L)
  (cond ((not L) nil)
        ((not (cdr L)) (car L))
        (t (last (cdr L)))))

(defun max3 (n1 n2 n3)
  (cond
   ((and (>= n1 n2) (>= n1 n3)) n1)
   ((and (>= n2 n1) (>= n2 n3)) n2)
   ((and (>= n3 n1) (>= n3 n2)) n3)))

Atoms, Pairs and Lists

List Manipulation

Other List Operations

Lisp Built-in Names