Lisp Examples Using Defun


>(setf route '(boston cambridge lincoln concord))


>(setf meals '(breakfast lunch tea dinner))


(defun both-ends (whole-list)

(cons (first whole-list)

(last whole-list)))


>(both-ends meals) ;;whole-list is undefined after the procedure call is done

(BREAKFAST DINNER)

>(both-ends route)

(BOSTON CAMBRIDGE)


;;Global value version....(not recommended)

(defun both-ends-global () ;;no parameters

(setf whole-list ;;whole-list is global

(cons (first whole-list) (last whole-list))))


>(setf whole-list '(monday tuesday wednesday thursday))

>(both-ends-global whole-list)

(MONDAY THURSDAY)

>whole-list ;; the global value is changed by the function

(MONDAY THURSDAY)


LET - a way to use local variables:


(defun both-ends-local (whole-list)

(let ((element (first whole-list))

(trailer (last whole-list))) ;;end of local inialization list

(cons element trailer))) ;;end of LET and end of procedure


LET evaluates initial-value forms in parallel:

>(setf x 'outside)

>(let ((x 'inside)

(y x)) ;; here x is still OUTSIDE

(list x y))

(INSIDE OUTSIDE)


LET* evaluates initial-value forms sequentially

>(setf x 'outside)

>(let* ((x 'inside)

(y x)) ;; x has been changed to INSIDE at this point

(list x y))

(INSIDE INSIDE)

TRY DOING EXERCISES 3-1 through 3-5 for practice