Functional Programming 02 Lists

Slides:



Advertisements
Similar presentations
09 Examples Functional Programming. Tower of Hanoi AB C.
Advertisements

CS 63 LISP Philip Greenspun's Tenth* Rule of Programming:
ANSI Common Lisp 3. Lists 20 June Lists Conses List Functions Trees Sets Stacks Dotted Lists Assoc-lists.
Lists in Lisp and Scheme a. Lists are Lisp’s fundamental data structures, but there are others – Arrays, characters, strings, etc. – Common Lisp has moved.
Lisp II. 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)
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
1 Programming Languages and Paradigms Lisp Programming.
Lisp II. 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)
Higher Order Functions “I hope you’re convinced, by now, that programming languages with first-class functions let you find more opportunities for abstraction,
Lisp Recitation (cse471/598 Fall 2007 ) Aravind Kalavagattu.
1 LISP III. 2 Functional programming l Definition From the "comp.lang.functional FAQ" Functional programming is a style of programming that emphasizes.
Alok Mehta - Programming in Lisp - Lecture Programming in Lisp Lecture 6 - Structure; Case Study: Blocks World.
Project 1: Background Informed search : 8- puzzle world BFS, DFS and A* algorithms Heuristics : Manhattan distance, Number of misplaced tiles Lisp programming.
Introduction to Artificial Intelligence Lisp Ruth Bergman Fall 2002.
CSCI Programming in Lisp; Instructor: Alok Mehta; 3_structs.ppt1 CSCI 2210: Programming in Lisp Programming Techniques Data Structures More Built-in.
First Lecture on Introductory Lisp Yun Peng. Why Lisp? Because it’s the most widely used AI programming language Because AI researchers and theoreticians.
CMSC 471 LISP. Why Lisp? Because it’s the most widely used AI programming language Because it’s good for writing production software (Graham article)
Introductory Lisp Programming Lecture # 2 Main Topics –Basic Lisp data types –Lisp primitives –Details of list handling Cons cells (boxes) & their representation.
General pattern for selecting some elements of a list This negatives example illustrates a general pattern: If you want a function which selects some elements.
LISP A brief overview. Lisp stands for “LISt Process” –Invented by John McCarthy (1958) –Simple data structure (atoms and lists) –Heavy use of recursion.
COMP 205 – Week 11 Dr. Chunbo Chu. Intro Lisp stands for “LISt Process” Invented by John McCarthy (1958) Simple data structure (atoms and lists) Heavy.
Spring 2008Programming Development Techniques 1 Topic 6 Hierarchical Data and the Closure Property Section September 2008.
LISP 1.5 and beyond A very quick tour. Data Atoms (symbols) including numbers – All types of numbers including Roman! (well, in the early days) – Syntactically.
F UNCTIONAL P ROGRAMMING 05 Functions. F UNCTIONS - G LOBAL F UNCTIONS fboundp Tells whether there is a function with a given symbol as its name > (fboundp.
Advanced Functions In CL, functions are often supplied as parameters to other functions –This gives us tremendous flexibility in writing functions whose.
Functional Programming
COMMON LISP.
PRACTICAL COMMON LISP Peter Seibel 1.
PRACTICAL COMMON LISP Peter Seibel 1.
Mitthögskolan 10/8/ Common Lisp LISTS. Mitthögskolan 10/8/2015 2Lists n Lists are one of the fundamental data structures in Lisp. n However, it.
1 Lists in Lisp and Scheme. 2 Lists are Lisp’s fundamental data structures. Lists are Lisp’s fundamental data structures. However, it is not the only.
Basic Lisp CIS 479/579 Bruce R. Maxim UM-Dearborn.
For Monday Read Chapter 3 Homework: –Lisp handout 2.
1 Lisp Functions –Built-in functions –Defining functions –Function Evaluation and Special Forms defun, if Control statements –Conditional if, cond –Repetition.
Lecture 2-1CS250: Intro to AI/Lisp Intelligent Agents Lecture 3-2 October 14 th, 1999 CS250.
04 Control. Control-Blocks Common Lisp has 3 basic operators for creating blocks of code progn block tagbody If ordinary function calls are the leaves.
06 INPUT AND OUTPUT Functional Programming. Streams Two kinds of streams  Character streams  Binary streams Character streams are Lisp objects representing.
Lecture 6-2CS250: Intro to AI/Lisp Programming in Your Favorite Language Lecture 5-2 February 11 th, 1999 CS250.
Recursive Data Structures and Grammars  Themes  Recursive Description of Data Structures  Recursive Definitions of Properties of Data Structures  Recursive.
Introduction to ACL2 CS 680 Formal Methods for Computer Verification Jeremy Johnson Drexel University.
LISP Data Types Functional Programming Academic Year Alessandro Cimatti
Building user-defined functions: the progressive envelopment technique The idea: define combinations of LISP primitives through a sequence of experiments.
Introduction to LISP. Lisp Extensible: It lets you define new operators yourself Lisp programs are expressed as lisp data structures –You can write programs.
11 Speed & Debug.  Lisp is really two languages:  A language for writing fast programs  A language for writing programs fast  In the early stage,
UMBC CMSC Common Lisp II. UMBC CMSC Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The.
Variables, Values, Atoms, Lists Variables in Lisp differ from other languages –They are not declared by type their type is determined at run-time, and.
Control in LISP More on Predicates & Conditionals.
You can access the members of a list with the functions car (or first) and cdr (or rest): (setf list '(a b c)) (car list) ⇒ a (first list) ⇒ a (cdr list)
Operating on Lists Chapter 6. Firsts and Seconds n Transforming list of pairs into two lists –(firsts ‘((1 5) (2 6) (3 7)))  (1 2 3) –(seconds ‘((1 5)
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
Lists CSC 358/ Outline Lab #1 / Homework #1 Lists A question List Internals of Lists List operations Extended Example.
Basic Introduction to Lisp
Search as a problem solving technique. Consider an AI program that is capable of formulating a desired goal based on the analysis of the current world.
Section 15.4, 15.6 plus other materials
Intelligent Agents Lecture 3-2 October 14th, 1999 CS250 Lecture 2-1
Example of formula (defun roots (a b c) (list
Lists in Lisp and Scheme
LISP A brief overview.
Using Lisp Lisp is a interactive system
First Lecture on Introductory Lisp
J.E. Spragg Mitthögskolan 1997
Modern Programming Languages Lecture 21 Fakhar Lodhi
LISP A brief overview.
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
Abstraction and Repetition
Common Lisp II.
Lisp.
List manipulation Consider student database, where each student is represented by the following list: * (setf student1 '((Paul Bennett) ((hw1 4.3) (hw2.
LISP primitives on sequences
Lists in Lisp and Scheme
Presentation transcript:

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 What 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) > (enigma ‘((a b) nil c)) T

Lists-Cons LisP  List Processor Cons Combine two objects into a two-part object A cons is a pair of pointers Car Cdr Provide a convenient representation for pairs of any type

Lists-Cons > (setf x (cons ‘a nil)) (A) The resulting list consists of a single cons > (car x) A > (cdr x) NIL

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

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

Lists-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 list

Lists-Equality Each time we call cons, Lisp allocates a new piece of memory with room for two pointers > (eql (cons ‘a nil) (cons ‘a nil)) NIL The two objects look the same, but are in fact distinct eql Returns true only if its arguments are the same object > (setf x (cons ‘a nil)) (A) > (eql x x) T

Lists-Equality equal Returns 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)))))

Lists-Why Lisp Has No Pointers Variables have values ~Lists have elements Variables have pointers to their values Lisp handles pointers for you > (setf x ‘(a b c)) (A B C) > (setf y x) (A B C) > (eql x y) T

Lists-Why Lisp Has No Pointers Assign a value to a variable or Store 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 don’t have to think about it

Lists-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

Lists-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)

Exercise Show the following lists in box notation (a b (c d))

Lists-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)

Lists-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)))) > (list-of 3 ‘ho) (HO HO HO) > (uncompress ‘((3 1) 0 1 (4 0) 1) (1 1 1 0 1 0 0 0 0 1))

Lists-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))))

Lists-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))

Lists-Trees Conses can also be considered as binary trees (a (b c) d) Car: left subtree Cdr: right subtree (a (b c) d)

Lists-Trees Common Lisp has several built-in functions for use of trees copy-tree subst (defun our-copy-tree (tr) (if (atom tr) tr (cons (our-copy-tree (car tr)) (our-copy-tree (cdr tr))))) Compare it with copy-list

Lists-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

Lists-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 ) ) ) ) ))

Lists-Recursion Advantage: let us view algorithms in a more abstract way (defun len (lst) (if (null lst) 0 (+ (len (cdr lst)) 1))) We should ensure that It works for lists of length 0 It works for lists of length n, and also for lists of length n+1

Lists-Recursion Don’t omit the base case of a recursive function Exercises (defun our-member (obj lst) ;it’s a wrong prog (if (eql (car lst) obj) lst (our-member obj (cdr lst))))

Lists-Sets Lists are a good way to represent small sets Every 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))

Lists-Sets > (member ‘a ‘((a b) (c d)) :key #’car) ((A B) (C D)) Ask if there is an element whose car is a Ask 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)

Lists-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)))))

Lists-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)

Lists-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)

Lists-Sequences Palindrome: 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

Lists-Sequences > (sort ‘(0 2 1 3 8) #’>) (8 3 2 1 0) Sort is destructive!! Exercise Use 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) #’>)))

Lists-Sequences > (every #’oddp ‘(1 3 5)) ;everyone is … T > (some #’evenp ‘(1 2 3)) ;someone is … T > (every #’> ‘(1 3 5) ‘(0 2 4)) T

Lists-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)

Lists-Dotted Lists Proper 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)

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

Lists-Example: Shortest Path (setf my-net ‘((a b c) (b c) (c d)) > (cdr (assoc ‘a my-net)) (B C)

Lists-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))))

Lists-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))

Lists-Garbage Automatic memory management is one of Lisp’s most valuable features The 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 heap Garbage 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

Lists Homework Bonus assignment Suppose 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 assignment Write 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)