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.

Slides:



Advertisements
Similar presentations
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.
Advertisements

C-LISP. LISP 2 Lisp was invented by John McCarthy in 1958 while he was at the Massachusetts Institute of Technology (MIT).John McCarthyMassachusetts Institute.
ANSI Common Lisp 5. Control 16 June Blocks -- progn progn > (progn (format t “a”) (format t “b”) ( )) ab 23 The expressions within its body.
1 Programming Languages and Paradigms Lisp Programming.
Recursion vs. Iteration The original Lisp language was truly a functional language: –Everything was expressed as functions –No local variables –No iteration.
A problem with functions: arguments must always have values that can be worked out Whenever we call a function we give it arguments. Lisp then works out.
1 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.
1 Introduction of Lisp function e.g. (+ 2 2) Shift+Enter Execute …… (+ 1 2) 3 ( ) 15 (- 1 6) -5 ( ) -5 (- ( ) (+
Lisp – Introduction יעל נצר מערכות נבונות סמסטר ב' תשס"ו.
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.
Introduction to Artificial Intelligence Lisp Ruth Bergman Fall 2002.
(cons ) (defun pair_elements (A B) ) (cond ( (or (null A) (null B) ) ‘() ) ( t ) (list ) Pairing elements in two lists >(pair_elements ‘(jack bonnie romeo)
Common Lisp! John Paxton Montana State University Summer 2003.
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.
First Lecture on Introductory Lisp Yun Peng. Why Lisp? Because it’s the most widely used AI programming language Because AI researchers and theoreticians.
Introduction CSC 358/458 3/27/2006. Outline Introductions Course goals Course organization History of Lisp Lisp syntax Examples Lisp IDE.
LISP primitives on sequences FIRST (or CAR) and REST (or CDR) take lists apart. Consider the list (First day of the semester). * (first '(First day of.
How to load a program file? Lisp programs in Allegro are saved under the file extension.cl. To load a file into the Lisp console, use the following: (load.
Programming in Lisp; Instructor: Alok Mehta Programming in Lisp Recursion, Data Abstraction, Mapping, Iteration.
Symbolic Expressions (S Expressions) Syntax: Opening and Closing parenthesis having elements in between. List represented in LISP: (A B2 C3 Shahid) (A.
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
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.
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.
Allegro CL Certification Program Lisp Programming Series Level I Session Top Ten Things to Know.
For Wednesday Read Chapter 4, sections 1 and 2 Homework: –Lisp handout 3.
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.
The Case primitive: matches the evaluated key form against the unevaluated keys by using eql The general format of case is the following: (case (... ).....
Functional Programming Here we briefly look at what functional programming is and why we want to study it –a function, in the mathematical sense, is a.
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.
Wednesday, October 20 (Blue) Thursday, October 21 (Gold) Objective Students add and subtract fractions and mixed numbers Fill in planner Today’s Assignment.
CSE 341, S. Tanimoto Lisp Defining Functions with DEFUN Functions are the primary abstraction mechanism available in Lisp. (Others are structures.
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.
ITEC 380 Organization of programming languages Lecture 5 – Functional Programming.
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.
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,
PRACTICAL COMMON LISP Peter Seibel 1.
UMBC CMSC Common Lisp II. UMBC CMSC Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The.
PRACTICAL COMMON LISP Peter Seibel 1.
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.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
Introduction to LISP Atoms, Lists Math. LISP n LISt Processing n Function model –Program = function definition –Give arguments –Returns values n Mathematical.
Functional Programming: Lisp MacLennan Chapter 10.
From Lambda Calculus to LISP Functional Programming Academic Year Alessandro Cimatti
Functional Programming “When I code in C, I feel I'm on a knife-edge of ‘state’ — I focus on statements and what they do. I'm worried about the behaviour.
1 Outline Review Introduction to LISP Symbols and Numbers Lists Writing LISP Functions LISPWorks.
Example of formula (defun roots (a b c) (list
Modern Programming Languages Lecture 20 Fakhar Lodhi
Getting Started with Lisp
LISP A brief overview.
First Lecture on Introductory Lisp
FP Foundations, Scheme In Text: Chapter 14.
Modern Programming Languages Lecture 21 Fakhar Lodhi
CS 36 – Chapter 11 Functional programming Features Practice
Modern Programming Languages Lecture 20 Fakhar Lodhi
CSE S. Tanimoto Explicit Function Application
LISP A brief overview.
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
Defining Functions with DEFUN
Abstraction and Repetition
Functional Programming: Lisp
Common Lisp II.
Lisp.
The general format of case is the following: (case <key form>
LISP primitives on sequences
Presentation transcript:

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 n Dotimes, dolist & do allow more general iteration –often used with side-effects

Review of Do n Do takes list of local variables, stopping condition plus return expression and body > (do ((i 1 (1+ i))) ((> i 10) ‘done) (format t “~a ” i)) DONE

DoTimes Example n Exponentiation function –(power 5 3) => 125 (defun power (M N) (setf result 1) (dotimes (i N result) (setf result (* M result)))) extra form in defun just for the side effect body of the loop done for the side effect loop control variable upper bound of the loop return value

DoTimes Operation (dotimes (i N result) ) (dotimes (i N res) (setf res (* M res))) for ( i = 0; i for ( i = 0; i return result; for ( i = 0; i < N; i++) res = M * res; return res; Loop control variable is not evaluated Upper bound is evaluated before 1 st iteration Return result is evaluated after last iteration Body evaluated once per iteration

DoTimes Factorial n Loop control variable available in the loop –just like loop control in imperative languages (defun factorial (N) (setf fact 1) (dotimes (i N fact) (setf fact (* (1+ i) fact)))) Need to add 1 to i, because i runs from 0 to N–1, not 1 to N

Exercise n Write a function using dotimes to calculate the sum of the numbers from 1 to N –can you do it without adding 1 to i each time?

Solution (defun sum-to-N (N) (setf sum 0) (dotimes (i (1+ N) sum) (setf sum (+ sum i)))) n Run loop to N+1 so we get sum 0..N –0 adds nothing to the sum, so that’s OK n Alternative: (dotimes (i N (+ sum N)) …)

Local vs. Global Variables n Functions above use global variables –not good – what if someone was using them already? –what if one of the functions called uses the same global variable? n Would like all the variables to be local n LISP gives us let and let*

Let n Let defines & initializes local variables > (let ((v1 10) (v2 5)) (+ v1 v2)) 15 > v1 ERROR: undefined variable n (let ) –value of becomes value of let

Using Let (defun power (M N) (let ((result 1)) (dotimes (i N result) (setf result (* M result)))) n result now local – no complications n Note: ((result 1)) –list of variable-value pairs –each pair in its own list

Let with Multiple Variables n Can use as many as you like (defun correlation (X Y) (let ((N (length X)) (Sx (sum-list X)) (Sy (sum-list Y)) (Sxy (dot-product X Y)) (Sxx (sum-of-squares X)) (Syy (sum-of-squares Y))) (/ (– (* N Sxy) (* Sx Sy)) (* …)))))

Exercise n Rewrite factorial and sum-to-N using lets (defun factorial (N) (setf fact 1) (dotimes (i N fact) (setf fact (* (+ i 1) fact)))) (defun sum-to-N (N) (setf sum 0) (dotimes (i (+ N 1) sum) (setf sum (+ sum i))))

Let Works in Parallel n All assignments are done “at the same time” –can’t use the value of one to set another > (let ((x 5) (y (+ x 10))) …) ERROR – unbound variable X n Won’t get an error if x is defined –you’ll just get the other value of x –(let ((x 5) (y (+ x 10))) (+ x y)) => 796 (!!!) “other” X was 781

Let* Works in Serial n In case you want to set one value based on another > (let* ((x 5) (y (+ x 10))) (+ x y)) 20 n X is already a local variable by the time let* gets to it

DoList n DoList allows iteration over lists –do something for each element of a list –also usually with side-effects n (dolist ( ) ) – set to each element of in turn – evaluated for each value – evaluated & returned

DoList Example n (do-reverse ‘( )) => ( ) (defun do-reverse (L) (let ((rev ())) (dolist (e L rev) (setf rev (cons e rev))))) n Elements added to front of rev –rev = (), (cons 1 rev) => (1) –rev = (1), (cons 2 rev) => (2 1)

Sum-List Using DoList > (defun sum-list (L) (let ((sum 0)) (dolist (e L sum) (setf sum (+ sum e))))) > (sum-list ‘(4 7 15)) sum  0 e  4, sum  (+ 0 4) => 4 e  7, sum  (+ 4 7) => 11 e  15, sum  ( ) => 26 => sum => 26

Exercise n Write the function do-intersect, to calculate the intersection of two lists using let and dolist > (do-intersect ‘( ) ‘( )) (9 3)

Solution n Iterate thru first list –if current element is in second list, add it to the intersection –intersection should have started as empty (defun do-intersection (L1 L2) (let ((inter ())) (dolist (e L1 inter) (when (member e L2) (push e inter)))))

Next Time n Applications –chapters 24 & 26