66 2210 - Programming in Lisp; Instructor: Alok Mehta1 66-2210-01 Programming in Lisp Recursion, Data Abstraction, Mapping, Iteration.

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.
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)
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 – Introduction יעל נצר מערכות נבונות סמסטר ב' תשס"ו.
Fall 2008Programming Development Techniques 1 Topic 3 Linear Recursion and Iteration September 2008.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
Chapter 10 Recursion Instructor: alkar/demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe.
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.
Functional programming: LISP Originally developed for symbolic computing Main motivation: include recursion (see McCarthy biographical excerpt on web site).
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
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.
>(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?
1 Chapter 1: Introduction What you have learnt in Comp1220 or Comp1170? What will be taught in Comp 1200? - more Abstract Data Types -efficient algorithms.
Mapping And Iteration So far, the only Lisp mechanism we have considered, which allows an action to be performed repeatedly is recursion. Most programming.
Symbolic Expressions (S Expressions) Syntax: Opening and Closing parenthesis having elements in between. List represented in LISP: (A B2 C3 Shahid) (A.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
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.
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.
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.
For Wednesday Read Chapter 4, sections 1 and 2 Homework: –Lisp handout 3.
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 (... ).....
Ceng-112 Data Structures I Chapter 6 Recursion.
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.
KU NLP Artificial Intelligence1 Ch 15. An Introduction to LISP q 15.0 Introduction q 15.1 LISP: A Brief Overview  Symbolic Expressions, the Syntactic.
CSE 341, S. Tanimoto Lisp Defining Functions with DEFUN Functions are the primary abstraction mechanism available in Lisp. (Others are structures.
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.
CSCI 2210: Programming in Lisp
Basic LISP Programming Common LISP follows the algorithm below when interacting with users: loop read in an expression from the console; evaluate the expression;
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 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.
11 Speed & Debug.  Lisp is really two languages:  A language for writing fast programs  A language for writing programs fast  In the early stage,
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.
1 Variable Declarations Global and special variables – (defvar …) – (defparameter …) – (defconstant …) – (setq var2 (list 4 5)) – (setf …) Local variables.
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.
From Lambda Calculus to LISP Functional Programming Academic Year Alessandro Cimatti
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
Recursion by Ender Ozcan. Recursion in computing Recursion in computer programming defines a function in terms of itself. Recursion in computer programming.
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
1 Outline Review Introduction to LISP Symbols and Numbers Lists Writing LISP Functions LISPWorks.
Artificial Intelligence and Lisp Lecture 6 LiU Course TDDC65 Autumn Semester,
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Example of formula (defun roots (a b c) (list
Modern Programming Languages Lecture 20 Fakhar Lodhi
Using Lisp Lisp is a interactive system
First Lecture on Introductory Lisp
Functional Programming
Modern Programming Languages Lecture 20 Fakhar Lodhi
LISP A brief overview.
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
CSC 143 Recursion.
Abstraction and Repetition
Functional Programming: Lisp
Lisp.
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.
LISP primitives on sequences
Procedures with optional parameters which do not require matching arguments Example: consider the exponent function which may take one argument, m, in.
Presentation transcript:

Programming in Lisp; Instructor: Alok Mehta Programming in Lisp Recursion, Data Abstraction, Mapping, Iteration

Programming in Lisp; Instructor: Alok Mehta2 Example: Both-ends  Define a procedure that gives both ends of a list > (setf itinerary ’(Albany NYC Chicago Seattle Anchorage)) > (both-ends itinerary) (ALBANY ANCHORAGE)  Three steps  Get first element > (first itinerary) ALBANY  Get last element > (first (last itinerary)) ANCHORAGE  Combine the two > (list (first itinerary) (first (last itinerary)))  Define procedure > (defun both-ends (l) (list (first l) (first (last l))))

Programming in Lisp; Instructor: Alok Mehta3 Error handling  Both-ends with error handling (defun both-ends (l) (if (listp l) (case (length l) (0 NIL) (1 (list (first l) (first l))) (t (list (first l) (first (last l))))) NIL))

Programming in Lisp; Instructor: Alok Mehta4 DoTimes  DOTIMES is Lisp’s way of doing iteration  C/C++ for (i=0; i<n; i++) { }  Lisp (dotimes (i n) )  First parameter is a list with three elements –counter variable (e.g. i) –number of times to iterate (e.g. n)  Counter variable (i) ranges from 0 to n-1  Optional return value can be specified (default is NIL) (dotimes (i n return_value) )

Programming in Lisp; Instructor: Alok Mehta5 Factorial  Definition of Factorial  C++ Implementation int factorial (int x) { int i,f; f = 1; for (i=1; i<=x; i++) f = f * i; return f; }  Lisp Implementation (defun factorial (n) (let ((f 1)) (dotimes (i n) (setf f (* f (+ i 1)))) f )  Tip: Compute factorial(100) using C/C++ and Lisp

Data Structures (Mehta)6 Recursively Calculating Factorial  Mathematical Definition of Factorial  C/C++ Implementation long Factorial (long X) { if (X <= 1) return 1; else return X * Factorial(X-1); }  Lisp Implementation (defun recursive-factorial (x) (if (<= x 1) 1 (* x (recursive-factorial (- x 1)))))

Programming in Lisp; Instructor: Alok Mehta7 Recursive calls  Show recursion when calling (recursive-factorial 4) Begin (recursive-factorial 4) Since 4>1, evaluate 4 * (recursive-factorial 3) Begin (recursive-factorial 3) Since 3>1, evaluate 3 * (recursive-factorial 2) Begin (recursive-factorial 2) Since 2>1, evaluate 2*(recursive-factorial 1) Begin (recursive-factorial 1) Since 1<=1, return 1 End (recursive-factorial 1), returns 1 2 * (recursive-factorial 1) = 2 * 1 = 2 End (recursive-factorial 2), returns 2 3 * (recursive-factorial 2) = 3 * 2 = 6 End (recursive-factorial 3), returns 6 4 * (recursive-factorial 3) = 4 * 6 = 24 End (recursive-factorial 4), returns 24

Data Structures (Mehta)8 Fibonacci Numbers  Mathematical Definition of Fibonacci Numbers  Sequence X Fib(X)  Recursive Solution (defun fib (x) (cond ((= x 0) 0) ((= x 1) 1) (t (+ (fib (- x 1)) (fib (- x 2))))))

Programming in Lisp; Instructor: Alok Mehta9 Fib(6) Function calls

Programming in Lisp; Instructor: Alok Mehta10 Recursive Definition of Length  Length (defun mylength (l) (if (endp l) 0 (+ 1 (mylength (rest l)))))  Alternate definition (defun mylength2 (l) (mylength2-aux l 0)) (defun mylength2-aux (l count) (if (endp l) count (mylength2-aux l (+ count 1))))  Note  All recursive calls simply return the final value evaluated.  No additional computations

Programming in Lisp; Instructor: Alok Mehta11 Tail Recursion  Tail Recursion  The final expression of a function is a recursive call  No additional computations are done to that expression –That is, return value is JUST the result of the recursive call  Lisp handles tail recursion efficiently  Mylength is not tail recursive  Mylength2 is tail recursive  Example:  Write a function to produce N atoms with value ‘A’. > (produce-list-of-a 5) ; Example call (A A A A A)

Programming in Lisp; Instructor: Alok Mehta12 Produce-list-of-a  Using dotimes (defun produce-list-of-a (n) (let ((la NIL)) (dotimes (i n la) (push 'A la))))  Recursion, not tail recursive (defun produce-list-of-a (n) (if (= n 0) nil (cons 'A (produce-list-of-a (- n 1)))))  Recursion, with tail recursion (defun produce-list-of-a (n) (produce-list-of-a-aux n NIL)) (defun produce-list-of-a-aux (n list-so-far) (if (= n 0) list-so-far (produce-list-of-a-aux (- n 1) (cons 'A list-so-far))))

Programming in Lisp; Instructor: Alok Mehta13 Count-Atoms  Write function to count number of atoms in an expr (sqrt (+ (expt x 2) (expt y 2))) has eight atoms (defun count-atoms (l) (cond ((null l) 0) ((atom l) 1) (t (+ (count-atoms (first l)) (count-atoms (rest l))))))

Data Structures (Mehta)14 Tower of Hanoi  Three pegs, S(start), T(temp), E(end)  N disks  Goal: Move disks from peg S to peg E  Restriction: Larger disk can’t be placed on top of smaller disk STE

Programming in Lisp; Instructor: Alok Mehta15 Tower of Hanoi  Solution to Tower of Hanoi (defun hanoi-aux (n start end temp) (if (> n 1) (hanoi-aux (- n 1) start temp end)) (print (list start end)) (if (> n 1) (hanoi-aux (- n 1) temp end start))) (defun hanoi (n) (hanoi-aux n 'S 'E 'T))  Example Runs > (hanoi 2) (S T) (S E) (T E) NIL > (hanoi 3) (S E) (S T) (E T) (S E) (T S) (T E) (S E) NIL

Programming in Lisp; Instructor: Alok Mehta16 &Optional  Produce-list-of-a function(s) (defun produce-list-of-a (n) (produce-list-of-a-aux n NIL)) (defun produce-list-of-a-aux (n list-so-far) (if (= n 0) list-so-far (produce-list-of-a-aux (- n 1) (cons 'A list-so-far))))  Redefined with optional parameters (defun produce-list-of-a (n &optional list-so-far) (if (= n 0) list-so-far (produce-list-of-a (- n 1) (cons 'A list-so-far))))  Note: optional values are bound to NIL, by default

Programming in Lisp; Instructor: Alok Mehta17 Optional Parameters (cont)  Solution to Hanoi (defun hanoi-aux (n start end temp) (if (> n 1) (hanoi-aux (- n 1) start temp end)) (print (list start end)) (if (> n 1) (hanoi-aux (- n 1) temp end start))) (defun hanoi (n) (hanoi-aux n 'S 'E 'T))  Revised with optional parameters (defun hanoi (n &optional (start 'S) (end 'E) (temp 'T)) (if (> n 1) (hanoi (- n 1) start temp end)) (print (list start end)) (if (> n 1) (hanoi (- n 1) temp end start)))  Note: notice the syntax for initializing optional parameters

Programming in Lisp; Instructor: Alok Mehta18 &Rest  &Rest - Specifies a variable number of arguments  Example: Assume + only accepts 2 arguments. Define “Plus”, a function that adds an arbitrary number of arguments) > (plus 2 3) > (plus )  Solution (defun plus (arg1 &rest other_args) (plus-aux arg1 other_args)) (defun plus-aux (arg1 other_args) (if (null other_args) arg1 (plus-aux (+ arg1 (first other_args)) (rest other_args))))

Programming in Lisp; Instructor: Alok Mehta19 Key Parameters  KEYword parameter  Useful when function has MANY parameters  Most are tied to default values  Examples > (rotate-list '(a b c d e)) ; rotate one element right (E A B C D) > (rotate-list '(a b c d e) :direction 'left) (B C D E A) > (rotate-list '(a b c d e) :distance 2) (D E A B C) > (rotate-list '(a b c d e) :direction 'left :distance 2) (C D E A B)

Programming in Lisp; Instructor: Alok Mehta20 &Key  Use &key to define Key parameters (defun rotate-list (l &key (direction 'right) (distance 1)) (if (eq direction 'left) (rotate-list-left l distance) (rotate-list-right l distance))) (defun rotate-list-right (l n) (if (zerop n) l (rotate-list-right (append (last l) (butlast l)) (- n 1)))) (defun rotate-list-left (l n) (if (zerop n) l (rotate-list-right (append (rest l) (list (first l))) (- n 1))))

Programming in Lisp; Instructor: Alok Mehta21 &Aux  &Aux keyword is used as a shorthand for Let*  Produce-list-of-a using Let* (defun produce-list-of-a (n) (let* ((la NIL)) (dotimes (i n la) (push 'A la))))  Using &Aux (defun produce-list-of-a (n &aux (la NIL)) (dotimes (i n la) (push 'A la)))