MC logo

Lisp loops


CS 231 Lecture Examples

<< Download
;
; The loop macro creates an infinite loop.
(defun fred1 (x) 
    (loop
        (if (null x) (return))
        (write (car x))
        (terpri)
        (setq x (cdr x))
    )  
)
;
; Good old for loop.
(defun fred2 (a b)
    (loop for x from a to b do
        (write x)
        (terpri)
    )
)
(defun fred3 (a b c)
    (loop for x from a to b by c do
        (write x)
        (terpri)
    )
)
;
; Good old while loop.
(defun fred4 (a b)
    (let ((x a))
        (loop while (<= x b) do
            (write x) (terpri)
            (setq x (* x 2))
        )
    )
)
;
; Accumulation is a good way to create return values from loops.  It adds
; its successive arguments to a list which becomes the return value.
(defun fred5 (a b c)
    (loop for x from a to b by c do
        collect x
    )
)
(defun fred6 (a b)
    (let ((x a))
        (loop while (<= x b) collect x do
            (setq x (* x 2))
        )
    )
)

<<