Dana Vrajitoru
C311 Programming Languages

Lisp Input-Output, Loops

While Loop

(while condition 
  sequence of expressions)

Examples

(defun count_div (x)
  (let ((count 0) (i 1))
    (while (<= i x)
       (if (eq (% x i) 0)
          (setq count (1+ count)))
       (setq i (+ 1 i)))
    count))
 (count_div 12)  ; => 6
(defun last (L)
  (let ((M L))
    (while (and M (cdr M))
      (setq M (cdr M)))
    (print L)
    (if M (car M) nil)))
(last '(1 2 3 4)) ;-> 4
(last ())         ;-> nil
(last '(1))       ;-> (1)

Simplified version of last considering that both car and cdr return nil when the list is empty:

(defun last (L)
  (let ((M L))
    (while (cdr M)
      (setq M (cdr M)))
    (car M)))
(last '(1 2 3 4)) ;-> 4
(last ())         ;-> nil
(last '(1))       ;-> 1

Function Parameters
All function parameters are value parameters in Lisp:

(defvar LL '(1 2 3 4))

(defun last (L)
  (while (and L (cdr L))
    (setq L (cdr L)))
  (car L))

(last LL)  ;=> 4
LL         ;=> (1 2 3 4)

(defun plus (x)
  (setq x (+ 1 x)))

(setq n 3) ;=> 3
(plus n)   ;=> 4
n          ;=> 3

Associative Lists

Mutators

List Mutators

Mutator Function

(defun set3rd (L val)
  (let ((M L))
    (setq M (cdr M))
    (setq M (cdr M))
    (setcar M val)
    L))
(setq L '(3 5 9 1 2))  ;=>  (3 5 9 1 2)
(set3rd L 10)          ;=>  (3 5 10 1 2)
L                      ;=>  (3 5 10 1 2)

Complex Conditional

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

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)))