MC logo

Functions as arguments


CS 231 Lecture Examples

<< Download >>
;
; It is possible to create an anonymous function.
(lambda (x) (+ x 1))

; 
; This is fairly useless unless you call it.
((lambda (x) (+ x 1)) 17)
; Which is a very verbose version of (+ 17 1)

;
; (mapcar f list) applies the function to each member of the list to give
; a new list.
(mapcar 'abs '(4 5 -3 -11 4))

;
; Mapcar can also work with multiple lists.  The number of lists must equal
; the arity of the function.
(mapcar '+ '(4 17 7) '(8 -5 21))

;
; Anonymous functions can be used with mapcar.
(mapcar (lambda (x) (+ x 1)) '(4 18 5 11 8))
(mapcar (lambda (x y) (+ (* x x) (* y y))) '(4 9 7 16) '(1 8 2 1))

;
; The reduce function will combine all the members of a list to
; form a result value which is the combination of these.  Here's
; a way to sum a list or take a product:
(reduce '+ '(4 9 2 1))   ; Equiv to (+ (+ (+ 4 9) 2) 1)
(reduce '* '(4 9 2 1))   ; Equiv to (* (* (* 4 9) 2) 1)

;
; Here's a brain-damaged, .. er.., interesting way to find the length of a 
; list.
(defun oddlen (lis) (reduce '+ (mapcar (lambda (x) 1) lis)))
(oddlen '(this is a list))

;
; This function selects the members of the list which satisfy the predicate.
; It is inconceivable that Common Lisp does not provide this somewhere as
; a standard function, but I cannot for the life of me find it.  It's probably
; called something obvious like idaho.
(defun select (f? lis)
    (cond
        ((null lis) ())
        ((funcall f? (car lis)) (cons (car lis) (select f? (cdr lis))))
        (t (select f? (cdr lis)))
    )
)

(select (lambda (x) (> x 10)) '(4 14 10 23 4 9 18))

;
; Here's a version of select sort on a lisp list.
(defun select_sort (lis)
    (if (or (null lis) (null (cdr lis)))
        lis
        (let*
            (
                (themax (reduce 'max lis))
                (maxes (select (lambda (x) (= x themax)) lis))
                (others (select (lambda (x) (/= x themax)) lis))
            )
            (append maxes (select_sort others))
        )
    )
)

(select_sort '(4 9 18 4 45 18 4 12 4 198 15 8))
(select_sort '(22))

<<
>>