CIS 400 LECTURE 12
More
Lisp:
Predicate
functions, continued:
>(null
'()) ;empty list
t
>(null
nil)
t
(null
t)
nil
>(null
sam)
nil
>(member
'a '(a b c)) ; find a list that has
"a" as an element
(a
b c)
>(member
'a '((a b) c (d e)) ; member is
top level only
nil
;
"not equal" in XLisp is /=
>(assoc
'c '((a b) (c d) (e f)) ; find
a sub-list with "c" as its "car"
(c
d)
;;;;;;; here's an interesting function!! ;;;;;;;;;;;;
>(and nil t t) ;short circuit boolean, if NO nil is
found, all are evaluated and last element ;is output
nil
>(and 'sam nil 'harry)
nil
>(and 1 2 3)
3
>(defun sign (a b)
(and (oddp a) (oddp b) 'both-odd)
)
>(sign 2 3)
nil
>(sign 3 3)
t
>(or nil t t) ;short circuit boolean, first t is
evaluated
t
>(or 'sam nil 'harry)
sam
>(or nil nil nil)
nil
>(defun sign (a b)
(or (oddp a) (oddp b)
'both-odd)
)
>(sign 2 3)
t
>(sign 3 3)
t
>(sign 2 2)
both-odd
>(defun compute (op x y)
(cond ((equal op 'sum) (+ x y))
((equal op 'prod) (* x y))
(t '(does not compute)) ;"t" will never evaluate as "nil", so
if previous 2
) ;condition
fail, the "t" results in the output "does not
) ;compute"
>(compute 'sum 2 3) ; similar to (+ 2 3)
5
>(compute 'subtract 3 2) ; all evaluations fail
(does not compute)
>(if (listp a) (car a)
'(not a list)
) ;
"if" is a predicate function found in Xlisp and ;common-Lisp
>(cond (( listp a) (car
a))
' (t '(not list))
) ;
similar function using "cond" instead of "if"
;;;;;;;;;;; creating local variables ;;;;;;;;;;;;;;;;;
>(defun augment (first
second) ;"first" and
"second" are passed parameters
(let ((item first) ;
"let" creates local variable
(bag second)
)
(if (listp first) (setq item second bag first))
(if (member item bag) bag (cons item bag))
)
)
>(augment 2 '(1 3))
(2 1 3) ;
adds 2 as new "car"
>(augment 2 '(1 2 3))
(1 2 3) ;
2 is already in list
>(defun count (L) ; this function will count number of
item in a list
® (do ((count 0 (+1 count)) ; initialize count to 0, then
increment by 1
(loaf L (cdr loaf))
((null loaf) count) ;
test to stop
¬ ) ;
ARROWS REPRESENT BEGINNING AND
) ;
END OF LOCAL VARIABLE SCOPE
>(count '(1 2 3))
3
;;;;;;;;;;; input and output ;;;;;;;;;;;;;
>(setq a (read))
>1 ; enter input
of "1"
>a ; ask to
output the value of "a"
1
>(setq a (read))
>(defun sum (x y) (+ x
y)) ; this actually makes Lisp
"read" the function that is
; is
defined by the input
>(eval
a) ;
what has been read is now evaluated
sum
>(sum
2 3)
5