Mapping And Iteration So far, the only Lisp mechanism we have considered, which allows an action to be performed repeatedly is recursion. Most programming.

Slides:



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

Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
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)
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)
Lambda Calculus and Lisp PZ03J. Lambda Calculus The lambda calculus is a model for functional programming like Turing machines are models for imperative.
List manipulation Consider student database, where each student is represented by the following list: * (setf student1 '((Paul Bennett) ((hw1 4.3) (hw2.
Lisp Recitation (cse471/598 Fall 2007 ) Aravind Kalavagattu.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
ITERATIVE CONSTRUCTS: DOLIST Dolist is an iterative construct (a loop statement) consisting of a variable declaration and a body The body states what happens.
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.
Common Lisp! John Paxton Montana State University Summer 2003.
Imperative programming public int factorial (int N){ int F = 1; for(X=N; X>1; X-- ){ F= F*X; } return F; } Functional programming (defun factorial(N) (cond.
Returning values from functions You can return a value from a function by using the built- in function : ( return-from Function_name value) For example:
>(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)
CSE S. Tanimoto Explicit Function Application 1 Explicit Application of Functions, Functional Arguments and Explicit Evaluation Implicit and explicit.
Programming in Lisp; Instructor: Alok Mehta Programming in Lisp Recursion, Data Abstraction, Mapping, Iteration.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
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.
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.
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.
Conditionals and Recursion "To iterate is human, to recurse divine." - L. Peter Deutsch.
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.
Recursion and Binary Tree ICS 51 – Introductory Computer Organization.
Input/Output Chapters 7 & 9. Output n Print produces output > (print 100) n It also returns the value it printed –that’s where the second 100 came.
Alok Mehta - Programming in Lisp - Data Abstraction and Mapping Programming in Lisp Data Abstraction and Mapping.
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.
The Loop Macro Many of the CL “functions” are actually macros (let, progn, if, etc) The most complicated macro in CL is probably the Loop macro –The Loop.
Lecture 6-2CS250: Intro to AI/Lisp Programming in Your Favorite Language Lecture 5-2 February 11 th, 1999 CS250.
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,
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.
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.
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
1 Variable Declarations Global and special variables – (defvar …) – (defparameter …) – (defconstant …) – (setq var2 (list 4 5)) – (setf …) Local variables.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
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.
Functional Programming: Lisp MacLennan Chapter 10.
CSE 341, S. Tanimoto Lisp Explicit Application of Functions and Functional Arguments In Lisp, functions can be passed as arguments to other functions.
Comparative Programming Languages Functional programming with Lisp/Scheme.
Ch Ch jcmt CSE 3302 Programming Languages CSE3302 Programming Languages (n-n-n-notes) Summer 2003 Dr. Carter Tiernan.
1 Outline Review Introduction to LISP Symbols and Numbers Lists Writing LISP Functions LISPWorks.
Section 15.4, 15.6 plus other materials
CS 550 Programming Languages Jeremy Johnson
Recursive Objects (Part 4)
Example of formula (defun roots (a b c) (list
Modern Programming Languages Lecture 20 Fakhar Lodhi
CS 270 Math Foundations of CS Jeremy Johnson
COP4020 Programming Languages
FP Foundations, Scheme In Text: Chapter 14.
Modern Programming Languages Lecture 20 Fakhar Lodhi
CSE S. Tanimoto Explicit Function Application
Lisp: Using Functions as Data
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
Peter Seibel Practical Common Lisp Peter Seibel
Abstraction and Repetition
Functional Programming: Lisp
Lisp: Using Functions as Data
Common Lisp II.
Allegro CL Certification Program
The general format of case is the following: (case <key form>
List manipulation Consider student database, where each student is represented by the following list: * (setf student1 '((Paul Bennett) ((hw1 4.3) (hw2.
Presentation transcript:

Mapping And Iteration So far, the only Lisp mechanism we have considered, which allows an action to be performed repeatedly is recursion. Most programming languages also have non- recursive constructs which allow the programmer to specify that an action is to be repeated

Mapping Functions Mapping functions are used when: The repetition is for each element (or subpart) of a list; The computation to be done each time is easily expressible as a function MAPCAR, MAPC

MAPCAR This function takes a function as an argument and applies it to all items of a given list, returning as a result a list of al the results thus obtained: To reverse each element of a list: > (mapc #’reverse ‘ ( (a b) (c d) (e f) (g h) ) ) ( (b a) (d c) (f e) (g h) ) >(mapcar #’first ‘( (a b) (c d) (e f))) (a c e) >(mapcar #’rest ‘( (a b) (c d) (e f))) ( (b) (d) (f) ) >(mapcar #’second ‘( (a b) (c d) (e f))) ( b d f )

MAPCAR with multiple lists We can give more than one list as argument to mapcar. Mapcar will apply the function to the corresponding elements in all the lists. For example, to add the corresponding elements in two lists: (mapcar #’+ (2 5 4) ( ) (7 8 9)) ( ) If we do this with lists of different lengths, mapcar will stop when it reaches the end of the shortest list: (mapcar #’+ (2) ( ) (7 8 9)) (19)

Mapcar example: remove elements iteratively > (remove_iterative ‘b ‘(a b c d b e f b)) (a c d e f) This can be done by: (defun remove_iterative (x list1) (apply #’append (mapcar #’(lambda (element) (cond ( (equal x element) ‘() ) ( t (list element) ) ) ) list1 ) ) ) This anonymous function returns every element except the one we’re removing. Each returned element is placed in a list Mapcar applies the function to each element in list1 and returns all results Since the function returns each element in a list (and an empty list for skipped elements), we have to append all the returned lists together

MAPC MAPC is like MAPCAR, but it doesn’t return a list of results. MAPC is used where the side-effect of the computation is required, but where the overall result of the computation is irrelevant. If the function given to MAPC needs more than one argument, then there should be as many lists of values supplied as it takes arguments: (mapc … )

MAPC example To print out all the items in the list listofvalues, each on a new line (where terpri outputs a new line), in between angle brackets: (defun printValues(listofvalues) (mapc #’(lambda (x) (print “<“) (print x) (print “>“) (terpri) ) listofvalues ) )

MAPC example: (mapc #’(lambda ( x y) (cond ((not (eql x y)) (print (list x y)))) ) ‘( ) ‘( ) ) (4 3) (11 10) Notice that if the lists are not all the same length, then the repetition terminates once the shortest list has been used up; the different lengths do not cause an error We have to use print to find out the results from MAPC: it doesn’t return the results in a list. MAPCAR is usually preferred.

Representing trees in lisp a cb dfe This is a tree. How would we represent a tree like this in Lisp? With lists. Each list represents a node in the tree, containing the node’s value and its left and right subnodes ( a )( b )( d ‘() ‘() )( e ‘() ‘() )( c ‘() )( e ‘() ‘() ) valueLeft nodeRight node

EXAMPLE EXERCISE: Functions for a tree-node data type: ;; node-value: function taking as argument  a list representing a node ;; returns associated value of a node (defun node-value (node) (first node)) ;; node-left: function taking as argument  a list representing a node ;; returns left –daughter node if any (defun node-left (node) (second node)) ;; node-right: function taking as argument  a list representing a node ;; returns right-daughter node if any (defun node-left (node) (third nd))

EXAMPLE – EXERCISE (cont.): ;; terminal: function taking as argument  item representing a node ;; returns T if no daughters of that node (the bottom of the tree) (defun terminal (node) (and (null (node-left node)) (null (node-right node))) ) ;; search-tree: function taking two arguments: 1. A node in a tree & ;; 2. An atom to be sought in the tree from that node downwards. ;; returns the sub tree which has that atom as its root (defun search-tree (tree target) (cond ((equal target (node-value tree)) tree) ; found it ((terminal tree) nil) ; run out of tree to search (t (or (search-tree (node-left tree) target) (search-tree (node-right tree) target)))))

EXAMPLE – EXERCISE (cont.): How would you write a function GET-ALL-VALUEs that takes a node and returns all the values in the tree with that node at its root (its top node?) Best to do this recursively!!! (defun get-all-values (node) (if (terminal node) (list (get-value node)) (apply #'append (get-all-values (node-left node)) (list (get-value node)) (get-all-values (node-right node)) ) ) )

EVERY The EVERY function operates in a similar way to MAPCAR, but is used for logical checking. The EVERY function returns a non-NIL result if the function supplied yields a non-NIL result on every element of the list > (every #’numberp ‘( )) t > (every #’numberp ‘(2 hello 3 5)) nil > (every #’= ‘(2 4 6) (list ( - 3 1) (+ 2 2) (* 2 3))) t

SOME This function returns a non-NIL result if the function yields a non-NIL result on some element of the list (or lists). > (some #’numberp ‘(a b 3 4)) t > (some #’numberp ‘(hello and welcome)) nil > (some #’= ‘(3 4 5) (list (-3 1) (+2 2) (*2 3))) t

Optional parameters It can sometimes be useful to define a function so that one or more arguments can be omitted in some of the uses of the function. For example: > (mklist 9) > (9) > (mklist 9 ‘(1 2 3)) > ( ) > (mklist 9 nil) > (9) How this can be done?  Optional arguments

Optional parameters (cont.) (defun function-name (req-arg &optional (optional-arg default-value) ) do whatever the function does ) (defun f (x &optional (y 10)) (list x y)) > (f 2) (2 10) > (f 2 5) (2 5) Caller has to give a value for req-arg. If they give a second arg it goes into optional-arg. Otherwise, opt-arg takes on given default-value. Optional arg called y Default value for y, used if none is given