Functions Robin Burke CSC 358/458 4.10.2006.

Slides:



Advertisements
Similar presentations
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 5. 2 List Utilities Scheme built-in procedures –(list x y z...) –(list-ref lst index) –(length lst) –(append.
Advertisements

Modern Programming Languages, 2nd ed.
1 Lecture 16: Tables and OOP. 2 Tables -- get and put.
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.
Introduction to Recursion and Recursive Algorithms
Some non-recursive tricks. The Lambda expression. More on Let, Let*, apply and funcall.
1 Programming Languages (CS 550) Mini Language Interpreter Jeremy R. Johnson.
Tail Recursion. Problems with Recursion Recursion is generally favored over iteration in Scheme and many other languages – It’s elegant, minimal, can.
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Winter 2013.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
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.
Introduction to Artificial Intelligence Lisp Ruth Bergman Fall 2002.
Introduction CSC 358/458 3/27/2006. Outline Introductions Course goals Course organization History of Lisp Lisp syntax Examples Lisp IDE.
>(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?
CSE S. Tanimoto Explicit Function Application 1 Explicit Application of Functions, Functional Arguments and Explicit Evaluation Implicit and explicit.
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.
CSC321: Programming Languages14-1 Programming Languages Tucker and Noonan Chapter 14: Functional Programming 14.1 Functions and the Lambda Calculus 14.2.
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.
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.
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.
TUTORIAL 2 CSCI3230 ( First Term) By Paco WONG 1.
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.
Functional Programming 02 Lists
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.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
CSE 341, S. Tanimoto Lisp Defining Functions with DEFUN Functions are the primary abstraction mechanism available in Lisp. (Others are structures.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
ITEC 380 Organization of programming languages Lecture 5 – Functional Programming.
Functional Programming in Scheme and Lisp.
Lecture 6-2CS250: Intro to AI/Lisp Programming in Your Favorite Language Lecture 5-2 February 11 th, 1999 CS250.
LISP Data Types Functional Programming Academic Year Alessandro Cimatti
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.
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.
Lists CSC 358/ Outline Lab #1 / Homework #1 Lists A question List Internals of Lists List operations Extended Example.
Basic Introduction to Lisp
Control Structures CSC 358/ Outline Midterm Lab #3 Homework #4 Sequential structures Conditional structures Unconditional branching Iteration.
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.
Ch Ch jcmt CSE 3302 Programming Languages CSE3302 Programming Languages (n-n-n-notes) Summer 2003 Dr. Carter Tiernan.
CS314 – Section 5 Recitation 9
CS314 – Section 5 Recitation 10
Functions CSC 358/
Section 15.4, 15.6 plus other materials
Edited by Original material by Eric Grimson
6.001 Jeopardy.
Example of formula (defun roots (a b c) (list
6.001 SICP Object Oriented Programming
PPL Lazy Lists.
CSE 341 Lecture 5 efficiency issues; tail recursion; print
Closure Closure binds a first-class function and a lexical environment together This is a complex topic, so we will build up our understanding of it we.
CSE S. Tanimoto Explicit Function Application
Explicit Application of Procedures, and Explicit Evaluation
Lisp: Using Functions as Data
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
Defining Functions with DEFUN
Abstraction and Repetition
Functional Programming: Lisp
Lisp: Using Functions as Data
Common Lisp II.
More Scheme CS 331.
LISP primitives on sequences
Presentation transcript:

Functions Robin Burke CSC 358/458 4.10.2006

Outline Errata Homework #2 Project Structures Functions Example review parameter lists anonymous fns closures recursion tail recursion Example

CLOS solution How many?

Errata append does cons it build a new list for the front part shares structure with the last part

Homework #2

Project Develop your own Lisp application Not restricted to implementing a game Timeline 4/17 Proposal 5/1 Accepted proposal 5/22 Progress report 6/7 Due

Structures Annoying to define a pile of accessors Alternative defstruct Defines a structure a named type with slots

defstruct Defines accessors mutators constructor read macro

Example (defstruct card suit rank) Defines make-card card-suit card-rank also #S(CARD :SUIT S :RANK 1) will be read and turned into a card object

Functions Defined with defun, but Real issue just a convenience symbol-function binding

Calling Functions Normal evaluation Others (+ 1 2 3) funcall apply avoid eval

Multiple values Let equivalent setq equivalent Example Also multiple-value-bind setq equivalent multiple-value-setq Example (multiple-value-bind (div rem) (floor num 10) ... rest of code ...) Also multiple-value-list

Example add-digits

Parameter Lists keywords rest optional (defun foo (a &key b c) ... ) (foo 5 :b 10 :c 19) (foo 5) rest (defun foo (&rest lst) ... ) (foo) (foo 10 15 25 30) optional (defun foo (a &optional b c) ... ) (foo 5 10 19)

Anonymous Functions Like anonymous classes in Java lambda but... lambda a macro that creates function objects (lambda (x) (* x x) Can create functions where needed useful as functional arguments (mapcar #'(lambda (x) (* x x)) '(1 2 3)) Can write functions to return functional values

Example numeric series

Closures Shared lexical variable Closure (defun integers () (let ((n 0)) (values #'(lambda () (incf n)) #'(lambda () (setf n 0))))) Closure binds variables in external scope keeps them when the scope disappears

Environment Evaluation takes place in an environment bindings for symbols Hierarchy of environments global environment local environments "Lexical context"

Example (let ((var1 (baz arg1 arg2))) #'(lambda () (foo var1)))) (defun bar (arg1 arg2) (let ((var1 (baz arg1 arg2))) #'(lambda () (foo var1)))) (setf fn (bar 'a 'b))

When Closure is Created

When Closure is Returned

Encapsulation Achieves OO goal variables in closure are totally inaccessible no way to refer to their bindings no way to even access that environment

Example Bank account

Compare with Java Anonymous classes External values only if instance variables final variables

Anonymous Class (illegal) JButton okButton = new JButton ("OK"); okButton.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent e) m_canceled = false; okButton.setEnabled(false); } });

Anonymous Class (legal) final JButton okButton = new JButton ("OK"); okButton.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent e) m_canceled = false; okButton.setEnabled(false); } }); // BUT okButton = new JButton ("Yep"); // Illegal

Simulating a Closure in Java final JButton [] arOkButton = new JButton [1]; arOkButton[0] = new JButton ("OK"); arOkButton[0].addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent e) m_canceled = false; arOkButton[0].setEnabled(false); } }); arOkButton[0] = new JButton ("Yep"); // Legal

Recursion Basic framework Why it works solve simplest problem "base case" solve one piece combine with the solution to smaller problem Why it works eventually some call = base case then all partial solutions are combined

Recursive Statement Some problems have a natural recursive statement maze following pattern matching

Example pattern matching

Double Recursion Trees Strategy operating on the "current" element isn't simple recurse on both car and cdr Strategy base case combine solution-to-car with solution-to-cdr

Example count-leaves

Recursive Stack (if (= 0 n) 1 (* n (factorial (1- n))) (defun factorial (n) (if (= 0 n) 1 (* n (factorial (1- n)))

Tail Recursion Avoid revisiting previous context New formulation = no after-the-fact assembly New formulation accumulate answer in parameter base case = return answer recursive step do partial solution and pass as answer parameter Effect do need to revist context recursive call = GOTO!

Tail Recursive Factorial (defun factorial (n) (factorial-1 n 1)) (defun factorial-1 (n ans) (if (= 0 n) ans (factorial-1 (1- n) (* n ans))))

Exercise average

Symbolic Programming Example iterators

Homework #3 Crazy Eights Create a playable game change the game state to use a closure add a function that chooses a move for the computer players

Lab