functional programming 02 lists

41
Functional Programming 02 Lists

Upload: wylie

Post on 14-Feb-2016

25 views

Category:

Documents


0 download

DESCRIPTION

Functional Programming 02 Lists. Review. > (cons ‘a ‘(b c d)) (A B C D) > ( list ‘a ‘b ‘c ‘d) (A B C D) > (car ‘(a b c d)) A > ( cdr ‘(a b c d)) (B C D). Review. Exercises - PowerPoint PPT Presentation

TRANSCRIPT

Slide 1

Functional Programming 02 ListsReview> (cons a (b c d))(A B C D)> (list a b c d)(A B C D)> (car (a b c d))A> (cdr (a b c d))(B C D)

2ReviewExercisesWhat does this function do?(defun enigma (x) (and (not (null x)) (or (null (car x)) (enigma (cdr x)))))> (enigma ((a b) (c nil d) e))NIL> (enigma nil)NIL> (enigma ((a b) nil c))T 3Lists-ConsLisP List ProcessorConsCombine two objects into a two-part objectA cons is a pair of pointersCarCdrProvide a convenient representation for pairs of any type

4Lists-Cons> (setf x (cons a nil))(A)The resulting list consists of a single cons

> (car x)A> (cdr x)NIL

5Lists-Cons> (setf y (list a b c))(A B C)

> (cdr y)(B C)

6Lists-Cons> (setf z (list a (list b c) d))(A (B C) D))

> (car (cdr z))(B C)

7Lists-Cons(defun our-listp (x) (or (null x) (consp x))) ; either null or a cons(defun our-atom (x) (not (consp x)))NIL is both an atom and a list8Lists-EqualityEach time we call cons, Lisp allocates a new piece of memory with room for two pointers> (eql (cons a nil) (cons a nil))NILThe two objects look the same, but are in fact distincteql Returns true only if its arguments are the same object> (setf x (cons a nil))(A)> (eql x x)T 9Lists-EqualityequalReturns true if its arguments would print the same> (equal x (cons a nil))T(defun our-equal (x y) (or (eql x y) (and (consp x) (consp y) (our-equal (car x) (car y)) (our-equal (cdr x) (cdr y)))))10Lists-Why Lisp Has No PointersVariables have values Lists have elementsVariables have pointers to their valuesLisp handles pointers for you> (setf x (a b c))(A B C)> (setf y x)(A B C)> (eql x y)T

11Lists-Why Lisp Has No PointersAssign a value to a variable orStore a value in a data structure store a pointer to the value x When you ask for the value of the variable or the contents of the data structure, Lisp returns what it points to ??All this happens beneath the surface you dont have to think about it12Lists-Building Lists> (setf x (a b c)) y (copy-list x))(A B C)

x and (copy-list x) will always be equal, and never eql unless x is nil

13Lists-Building Lists(defun our-copy-list (lst) (if (atom lst) lst (cons (car lst) (our-copy-list (cdr lst)))))

> (append (a b) (c d) (e))(A B C D E)14ExerciseShow the following lists in box notation(a b (c d))(a (b (c (d))))(((a b) c) d)15Lists-Example: Run-length coding(defun compress (x) (if (consp x) (compr (car x) 1 (cdr x)) x))(defun compr (elt n 1st) ;find elt from lst, the current length is n (if (null lst) (list (n-elts elt n)) (let ((next (car lst))) (if (eql next elt) (compr elt (+ n 1) (cdr lst)) (cons (n-elts elt n) (compr next 1 (cdr lst) ) ) ) ) ) )(defun n-elts (elt n) ;output (n elt) (if (> n 1) (list n elt) elt ) )

> (compress (1 1 1 0 1 0 0 0 0 1))((3 1) 0 1 (4 0) 1)

16Lists-Example: Run-length coding(defun uncompress (lst) (if (null lst) nil (let ((elt (car lst)) (rest (uncompress (cdr lst)))) (if (consp elt) (append (apply #list-of elt) rest (cons elt rest)))))(defun list-of (n elt) ;output n elt (if (zerop n) nil (cons elt (list-of (- n 1) elt)))) > (uncompress ((3 1) 0 1 (4 0) 1) (1 1 1 0 1 0 0 0 0 1))

> (list-of 3 ho)(HO HO HO)

17Lists-Access> (nth 0 (a b c))A> (nthcdr 2 (a b c))(C)nth car of nthcdr(defun our-nthcdr (n lst) (if (zerop n) lst (our-nthcdr (- n 1) (cdr lst)))) 18Lists-Mapping Functions> (mapcar #(lambda (x) (+ x 10)) (1 2 3))(11 12 13)> (mapcar #list (a b c) (1 2 3 4))((A 1) (B 2) (C 3))> (maplist #(lambda (x) x) (a b c))((A B C) (B C) (C))19Lists-TreesConses can also be considered as binary treesCar: left subtreeCdr: right subtree(a (b c) d)

20Lists-TreesCommon Lisp has several built-in functions for use of treescopy-treesubst(defun our-copy-tree (tr) (if (atom tr) tr (cons (our-copy-tree (car tr)) (our-copy-tree (cdr tr)))))Compare it with copy-list21Lists-Trees> (substitute y x (and (integerp x) (zerop (mod x 2))))(AND (INTEGERP X) (ZEROP (MOD X 2)))Substitute: replaces elements in a sequence> (subst y x (and (integerp x) (zerop (mod x 2)))(AND (INTEGERP Y) (ZEROP (MOD Y 2)))Subst: replaces elements in a tree

22Lists-Trees(defun our-subst (new old tree) ( if (eql tree old) new ( if (atom tree) tree (cons (our-subst new old (car tree)) (our-subst new old (cdr tree ) ) ) ) ))

23Lists-RecursionAdvantage: let us view algorithms in a more abstract way(defun len (lst) (if (null lst) 0 (+ (len (cdr lst)) 1)))We should ensure thatIt works for lists of length 0It works for lists of length n, and also for lists of length n+124Lists-RecursionDont omit the base case of a recursive functionExercises (defun our-member (obj lst) ;its a wrong prog (if (eql (car lst) obj) lst (our-member obj (cdr lst))))

25Lists-SetsLists are a good way to represent small setsEvery element of a list is a member of the set it represent> (member b (a b c))(B C)> (member (b) ((a) (b) (c)))NIL Why?Equal: the same expression?Eql: the same symbol or number?member compares objects using eql> (member (a) ((a) (z)) :test #equal) ;:test-> keyword argument((A) (Z))26Lists-Sets> (member a ((a b) (c d)) :key #car)((A B) (C D))Ask if there is an element whose car is aAsk if there is an element whose car is equal to 2> (member 2 ((1) (2)) :key #car :test #equal) ((2))> (member 2 ((1) (2)) :test #equal :key #car) ((2))

27Lists-Sets> (member-if #oddp (2 3 4))(3 4)(defun our-member-if (fn lst) (and (consp lst) (if (funcall fn (car lst)) lst (our-member-if fn (cdr lst)))))28Lists-Sets> (adjoin b (a b c))(A B C)> (adjoin z (a b c))(Z A B C)> (union (a b c) (c b s))(A C B S)> (intersection (a b c) (b b c))(B C)> (set-difference (a b c d e) (b e))(A C D)29Lists-Sequences> (length (a b c))3> (length ((a b) c (d e f)))?> (subseq (a b c d) 1 2)(B)> (subseq (a b c d) 1)(B C D)> (reverse (a b c))(C B A)30Lists-SequencesPalindrome: a sequence that reads the same in either direction(defun mirror? (s) (let ((len (length s))) (and (evenp len) (let ((mid (/ len 2))) (equal (subseq s 0 mid) (reverse (subseq s mid)))))))> (mirror? (a b b a))T

31Lists-Sequences> (sort (0 2 1 3 8) #>)(8 3 2 1 0)Sort is destructive!!ExerciseUse sort and nth to write a function that takes an integer n, and returns the nth greatest element of a list(defun nthmost (n lst) (nth (- n 1) (sort (copy-list lst) #>)))32Lists-Sequences> (every #oddp (1 3 5)) ;everyone is T> (some #evenp (1 2 3)) ;someone is T> (every #> (1 3 5) (0 2 4))T33Lists-Stacks(push obj lst)pushes obj onto the front of the list lst(pop lst)removes and returns the first element of the list lst> (setf x (b))(B)> (push a x)(A B)> x(A B)> (setf y x)(A B)> (pop x)A> x(B)> y(A B)

34Lists-Dotted ListsProper list: is either nil, or a cons whose cdr is a proper list(defun proper-list? (x) (or (null x) (and (consp x) (proper-list? (cdr x)))))Dotted list:is an n-part data structure(A . B)(setf pair (cons a b))(A . B)

35Lists-Dotted Lists> (a . (b . (c . nil)))(A B C)> (cons a (cons b (cons c d)))(A B C . D)

36Lists-Example: Shortest Path(setf my-net ((a b c) (b c) (c d))

> (cdr (assoc a my-net))(B C)

37Lists-Example: Shortest Path(defun shortest-path (start end net) (bfs end (list (list start)) net))(defun bfs (end queue net) (if (null queue) nil (let ((path (car queue))) (let ((node (car path))) (if (eql node end) (reverse path) (bfs end (append (cdr queue) (new-paths path node net)) net))))))(defun new-paths (path node net) (mapcar #'(lambda (n) (cons n path)) (cdr (assoc node net))))

38Lists-Example: Shortest Path> (shortest-path a d my-net)(A C D)Queue elements when calling bfs successively((A))((B A) (C A))((C A) (C B A))((C B A) (D C A))((D C A) (D C B A))

39Lists-GarbageAutomatic memory management is one of Lisps most valuable featuresThe Lisp system maintains a segment of memory Heap Memory is allocated from a large pool of unused memory area called the heap (also called the free store). Consing: allocating memory from the heapGarbage collection (GC): the system periodically search through the heap, looking for memory that is no longer needed> (setf lst (list a b c)(A B C)> (setf lst nil)NIL 40ListsHomeworkSuppose the function pos+ takes a list and returns a list of each element plus its position:> (pos+ (7 5 1 4))(7 6 3 7)Define this function using (a) recursion, (b) iteration, (c) mapcar.(Due March 17)Bonus assignmentWrite a C program to find the shortest path in a network, just like the program in page 38, and analyze the differences between these two programs(Due March 24)41