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)

Slides:



Advertisements
Similar presentations
ANSI Common Lisp 3. Lists 20 June Lists Conses List Functions Trees Sets Stacks Dotted Lists Assoc-lists.
Advertisements

Lisp. Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks.
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)
CSE 341 Lecture 16 More Scheme: lists; helpers; let/let*; higher-order functions; lambdas slides created by Marty Stepp
List manipulation Consider student database, where each student is represented by the following list: * (setf student1 '((Paul Bennett) ((hw1 4.3) (hw2.
Higher Order Functions “I hope you’re convinced, by now, that programming languages with first-class functions let you find more opportunities for abstraction,
1-1 An Introduction to Scheme March Introduction A mid-1970s dialect of LISP, designed to be a cleaner, more modern, and simpler version than.
Lisp – Introduction יעל נצר מערכות נבונות סמסטר ב' תשס"ו.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
Commands and predicates LISP functions are divided into 2 classes. Predicates are functions that return boolean values i.e. t or nil. The rest are commands.
ITERATIVE CONSTRUCTS: DOLIST Dolist is an iterative construct (a loop statement) consisting of a variable declaration and a body The body states what happens.
Introduction to Artificial Intelligence Lisp Ruth Bergman Fall 2002.
Lisp. Versions of LISP Lisp is an old language with many variants –LISP is an acronym for List Processing language Lisp is alive and well today Most modern.
CSCI Programming in Lisp; Instructor: Alok Mehta; 3_structs.ppt1 CSCI 2210: Programming in Lisp Programming Techniques Data Structures More Built-in.
>(setf oldlist ) Constructing a list We know how to make a list in lisp; we simply write it: ‘4321( ) What if we want a new list with that list as a part?
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)
CS 330 Programming Languages 11 / 18 / 2008 Instructor: Michael Eckmann.
LISP A brief overview. Lisp stands for “LISt Process” –Invented by John McCarthy (1958) –Simple data structure (atoms and lists) –Heavy use of recursion.
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.
For Wednesday Read Chapter 4, sections 1 and 2 Homework: –Lisp handout 3.
Functional Programming 02 Lists
Alok Mehta - Programming in Lisp - Data Abstraction and Mapping Programming in Lisp Data Abstraction and Mapping.
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.
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.
ISBN Chapter 15 Functional Programming Languages.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
Common Lisp! John Paxton Montana State University Summer 2003.
Iteration Chapters 6 & 7. Iteration in LISP n LISP (unlike Prolog) allows iteration –mapcar, remove-if(-not), count-if, find-if for special purpose iteration.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
CSCI 2210: Programming in Lisp
Data Abstraction Chapter 6. Birthday Information n Suppose we want to represent information about people –perhaps for a family tree –name & date of birth,
Function Design in LISP. Program Files n LISP programs are plain text –DOS extensions vary; use.lsp for this course n (load “filename.lsp”) n Can use.
Lisp Functional Language or Applicative Language –Achieves its effect by applying functions, either recursively or through composition Powerful, expressive,
Predicates, Functions and Files "I suppose I should learn Lisp, but it seems so foreign." - Paul Graham, Nov 1983.
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.
UMBC CMSC Common Lisp II. UMBC CMSC Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The.
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)
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
Introduction to LISP Atoms, Lists Math. LISP n LISt Processing n Function model –Program = function definition –Give arguments –Returns values n Mathematical.
1 COSC generating functions, templates, and macros Yves Lespérance Adapted from Peter Roosen-Runge.
Basic Introduction to Lisp
Functional Programming: Lisp MacLennan Chapter 10.
CS 330 Programming Languages 11 / 28 / 2006 Instructor: Michael Eckmann.
Forms Writing your own procedures CS 480/680 – Comparative Languages.
Functional Programming Languages
Section 15.4, 15.6 plus other materials
Example of formula (defun roots (a b c) (list
Chapter 15 – Functional Programming Languages
LISP A brief overview.
First Lecture on Introductory Lisp
J.E. Spragg Mitthögskolan 1997
FP Foundations, Scheme In Text: Chapter 14.
CSE S. Tanimoto Explicit Function Application
LISP A brief overview.
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
Functional Programming: Lisp
Common Lisp II.
Programming Languages
Lisp.
List manipulation Consider student database, where each student is represented by the following list: * (setf student1 '((Paul Bennett) ((hw1 4.3) (hw2.
Presentation transcript:

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) (2 6) (3 7)))  (5 6 7) n Similar code (defun seconds (L) (unless (null L) (cons (second (first L)) (seconds (rest L))))) –replace “second” with “first” for firsts

Transforming a List n Programming cliché –transform a list into another list (defun (theList) (unless (null theList) (cons ( (first theList)) ( (rest theList))))) n Applies to each element – = second, for example

Transforming a List n Programming cliché –transform a list into another list (defun (theList) (unless (null theList) (cons ( (first theList)) ( (rest theList))))) n Applies to each element – = second, for example firsts firsts first

Transforming a List n Programming cliché –transform a list into another list (defun (theList) (unless (null theList) (cons ( (first theList)) ( (rest theList))))) n Applies to each element – = second, for example seconds seconds second

MAPCAR n A built in function for transforming lists –map each element – car to get an element (defun (theList) (mapcar #’ theList)) n Applies to each element of theList n Note the way the function appears: #’name

Using MAPCAR > (mapcar #’first ‘((1 5) (2 6) (3 7))) (1 2 3) > (mapcar #’second ‘((1 5) (2 6) (3 7))) (5 6 7) > (defun square (N) (expt N 2)) SQUARE > (mapcar #’square ‘( )) ( )

MAPCAR vs. Recursion (defun square-all (L) (unless (null L) (cons (square (first L)) (square-all (rest L))))) n Mapcar version more concise –easier to read –more efficient –performs exactly the same task (defun square-all (L) (mapcar #’square L))

Exercise > (mapcar #’third ‘((1 2 3) (a b c) (do re mi))) > (mapcar #’fourth ‘(( ) (x y z))) > (mapcar #’oddp ‘( )) > (mapcar #’list ‘(a b c d e)) > (defun sum-list (L) (if (null L) 0 (+ (first L) (sum-list (rest L))))) > (mapcar #’sum-list ‘(( ) (5 6 7) (8 5 2)))

“Helper” Functions n Recall the function that calculates the correlation of a list of pairs –(correlate-pairs ‘((5 3) (10 6) (15 12))) => –used the correlation function from last time (defun correlate-pairs (XYs) (correlation (firsts XYs) (seconds XYs))) n Needed to define firsts and seconds as separate functions

Avoiding Helpers n Use MAPCAR and avoid having to make those functions (defun correlate-pairs (XYs) (correlation (mapcar #’first XYs) (mapcar #’second XYs)))

Multi-Argument MAPCAR n May take a third, fourth, …, argument n Function argument is applied to firsts of all lists, then seconds, then thirds, &so on… > (mapcar #’+ ‘(1 2 3) ‘(4 5 6) ‘(7 8 9)) (1 2 3) (4 5 6) +(7 8 9) (121518)

Exercise > (mapcar #’* ‘(1 2 7) ‘(3 4 6)) > (mapcar #’expt ‘( ) ‘( )) > (mapcar #’ (mapcar #’< ‘( ) ‘( ) ‘( )) > (mapcar #’append ‘((1 2) (a b)) ‘((x y) (do re))) > (defun distance (P1 P2) (abs (– P1 P2))) > (mapcar #’distance ‘( ) ‘( ))

Other List Handling Functions n Some other common tasks have been abstracted into built-in functions –remove-ifreturns a shorter list –remove-if-notreturns a shorter list –count-ifcounts matching items in the list –find-ifreturns first matching item

Remove-If & Remove-If-Not n Use a predicate to eliminate/select items > (remove-if #’oddp ‘( )) (2 4 6) > (remove-if-not #’oddp ‘( )) ( )

Functions, Not Assignments n Remove-if & remove-if-not do not modify their argument > (setf aList ‘( )) ( ) > (remove-if #’oddp aList) (2 4 6) > aList ( ) Use (setf Var (remove-if … Var)) to change the value by removing items

Count-If n Use a predicate to count items > (count-if #’oddp ‘( )) 4 > (count-if #’evenp ‘( )) 3 n Equivalent to (length (remove-if-not F L)) –but more efficient

Find-If n Returns first item that satisfies the predicate > (find-if #’oddp ‘( )) 3 > (find-if #’evenp ‘( )) 2

Exercises > (remove-if #’numberp ‘(a 2 c (i v) 5)) > (remove-if-not #’atom ‘(a 2 c (i v) 5)) > (count-if #’symbolp ‘(a 2 c (i v) 5)) > (defun in-range (N) ( (defun in-range (N) (<= 0 N 100)) > (remove-if-not #’in-range ‘( – )) > (find-if #’in-range ‘( – )) > (find-if #’listp ‘(a 2 c (i v) 5))

Function Calling Functions n Funcall and apply call functions > (funcall #’ ) 21 > (apply #’+ ‘( )) 21 n Both same as ( )

Funcall, Apply & Eval n (funcall #’ )=( ) –four arguments –function + its arguments n (apply #’+ ‘(1 2 3))=( ) –two arguments –function + list of its arguments n (eval ‘( ))=( ) –one argument: form to be evaluated

Applying Functions to Lists n Apply used to apply functions to lists –list passed as an argument, perhaps –avoid recursive function calls > (defun sum-list (L) (apply #’+ L)) > (sum-list ‘( )) 21

APPLY vs. Recursion (defun sum-list (L) (if (null L)0 (+ (first L) (sum-list (rest L))))) n Apply version more concise –easier to read –more efficient –perform exactly the same task (defun sum-list (L) (apply #’+ L))

Dot Products n We defined a dot-product function last time –(dot-product ‘( ) ‘(3 6 9)) => 210 –5*3 + 10*6 + 15*9 = = 210 (defun dot-product (Xs Ys) (if (null Xs) 0 (+ (* (first Xs) (first Ys)) (dot-product (rest Xs) (rest Ys)))) n Can be written using apply and mapcar –use mapcar to multiply each pair of numbers –use apply to add up the resulting list

Dot Product n (mapcar #’* ‘( ) ‘(3 6 9)) => ( ) n (apply #’+ ‘( )) => 210 (defun dot-product (L1 L2) (apply #’+ (mapcar #’* L1 L2)))

Plus 1 List Revisited n Wanted to add 1 to each element of a list (defun plus1List (L) (unless (null L) (cons (+ 1 (first L)) (plus1List (rest L))))) n Using MAPCAR: (defun plus1List (L) (mapcar #’1+ L)) –1+ is the “add 1” function

Plus 2 List n Suppose we wanted to add 2 instead (defun plus2List (L) (unless (null L) (cons (+ 2 (first L)) (plus1List (rest L))))) n There is no 2+ function –need to write our own (defun 2+ (N) (+ N 2)) –how can we avoid that?

Lambda ( ) in LISP n Lambda expression is a way of specifying a function without giving it a name n Very much like defun – leave out the name (defun add-10 (x) (+ x 10)) (lambda (x) (+ x 10)) n Both give the same function –but defun gives it a name, too

Using Lambda Expressions n Can be used where-ever a function is –function arguments, in particular > (mapcar (lambda (x) (+ x 10)) ‘( )) ( ) > ((lambda (x) (+ x 10)) 5) 15 n Note: text has #’ in front of the expr. –may be necessary in some LISPs

Exercises n Evaluate the following: > (mapcar (lambda (x) (* x x)) ‘( )) > ((lambda (x) (numberp x)) ‘(a 2 c (i v) 5)) > (mapcar (lambda (x) (and (numberp x) (evenp x))) ‘(a 2 c (i v) 5))

Exercise n Write a function using mapcar and a lambda expression to double every element of a list > (double-all ‘( )) ( )

Lambda Variables n Lambda expressions use variables –parameter list –“open” variables n Looks for nearest definition of the variable –a parameter of this lambda expression –a parameter of an enclosing lambda/defun

Open Variables n We can write a function that adds a given amount to every element of a list > (add-to-each 5 ‘( )) ( ) n Can use first parameter as “open” in lambda > (defun add-to-each (Amt Lst) (mapcar (lambda (x) (+ Amt x)) Lst))

Exercise n Write a function using mapcar and a lambda expression that calculates the N th power of every element of a list (where N is given as the second parameter) > (nth-power-each ‘( ) 3) ( )

Exercise n Defun this function: –(mathify #’+ 5 ‘( ));; add 5 to each ( ) –(mathify #’* 4 ‘( ));; multiply each by 4 ( ) –(mathify #’/ 10 ‘( ));; divide each by 10 (1/10 1/5 3/10 2/5) –break it into steps!

Next Time n Data Abstraction –chapter 6