Download presentation
Presentation is loading. Please wait.
Published byAntwan Mallinson Modified over 9 years ago
1
Lisp II
2
How EQUAL could be defined (defun equal (x y) ; this is how equal could be defined (cond ((numberp x) (= x y)) ((atom x) (eq x y)) ((atom y) nil) ((equal (car x) (car y)) (equal (cdr x) (cdr y)))))
3
Some simple list processing examples (defun member (x theList) (cond ((atom theList) nil) ((equal x (car theList)) (cdr theList)) (T (member x (cdr theList)))) (defun append (l1 l2) (if (null l1) l2 (cons (car l1) (append (cdr l1) l2))))
4
Variations on reverse ;; either of these does O(n^2) cons operations (defun reverse (theList) (if (null theList) nil (append (reverse (cdr theList)) (list (car theList))))) (defun reverse (theList) (and theList (append (reverse (cdr theList)) (list (car theList)))))
5
Variations on reverse ;; this tail recursive operation does O(n) conses (defun reverse (theList) (reverse1 theList nil)) (defun reverse1 (theList acc) (if (null theList) acc (reverse (cdr theList) (cons (car theList) acc))))
6
Flatten I (defun flatten (theList) (cond ((null theList) nil) ; empty list do nothing ((atom (car theList)) ; cons an atom onto flattend cdr (cons (car theList) (flatten (cdr theList)))) ; otherwise flatten head & tail and append results (t (append (flatten (car theList)) (flatten (cdr theList))))))
7
Flatten II ;; this version avoids append, which is expensive. (defun flatten (theList) (flatten1 theList nil)) (defun flatten1 (theList acc) (cond ((null theList) acc) ; all done ((atom theList) ; stick atom on the front of acc (cons theList acc)) ; of the accumulator (t (flatten1 (car theList) (flatten1 (cdr theList) acc)))
8
Higher order functions (defun mapcar (f theList) (if (null theList) nil (cons (apply f (list (car theList))) (mapcar f (cdr theList)))))
9
Mapcar II (defun mapcar1 (f theList) (if (null theList) nil (cons (apply f (list (car theList))) (mapcar f (cdr theList))))) (defun mapcar (f &rest args) "Apply f to successive cars of all ARGS. Return the list of results." ;; If no list is exhausted, (if (not (memq 'nil args)) ; apply function to CARs. (cons (apply f (mapcar1 'car args)) (mapcar* f (mapcar1 'cdr args)))))
10
The End
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.