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.

Slides:



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

Functions Robin Burke CSC 358/
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.
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.
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)
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
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 COSC3306: Programming Paradigms Lecture 11: Applicative Programming with Lisp Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.
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.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
First Lecture on Introductory Lisp Yun Peng. Why Lisp? Because it’s the most widely used AI programming language Because AI researchers and theoreticians.
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.
Artificial Intelligence and Lisp Lecture 6 LiU Course TDDC65 Autumn Semester, 2010
Programming in Lisp; Instructor: Alok Mehta Programming in Lisp Recursion, Data Abstraction, Mapping, Iteration.
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.
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.
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
The Case primitive: matches the evaluated key form against the unevaluated keys by using eql The general format of case is the following: (case (... ).....
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.
1 Lists in Lisp and Scheme. 2 Lists are Lisp’s fundamental data structures. Lists are Lisp’s fundamental data structures. However, it is not the only.
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.
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,
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.
06 INPUT AND OUTPUT Functional Programming. Streams Two kinds of streams  Character streams  Binary streams Character streams are Lisp objects representing.
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.
Introduction to ACL2 CS 680 Formal Methods for Computer Verification Jeremy Johnson Drexel University.
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.
PRACTICAL COMMON LISP Peter Seibel 1.
Control in LISP More on Predicates & Conditionals.
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.
Basic Introduction to Lisp
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.
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,
Section 15.4, 15.6 plus other materials
Intelligent Agents Lecture 3-2 October 14th, 1999 CS250 Lecture 2-1
Example of formula (defun roots (a b c) (list
Modern Programming Languages Lecture 20 Fakhar Lodhi
LISP A brief overview.
Using Lisp Lisp is a interactive system
First Lecture on Introductory Lisp
J.E. Spragg Mitthögskolan 1997
Modern Programming Languages Lecture 21 Fakhar Lodhi
Modern Programming Languages Lecture 20 Fakhar Lodhi
CSE S. Tanimoto Explicit Function Application
Lisp: Using Functions as Data
LISP A brief overview.
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
Defining Functions with DEFUN
Abstraction and Repetition
Lisp: Using Functions as Data
Common Lisp II.
Lisp.
The general format of case is the following: (case <key form>
Presentation transcript:

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 ‘+) T > (symbol-function ‘+) # (setf (symbol-function ‘add2) #’(lambda (x) (+ x 2))) > (add2 1) 3

F UNCTIONS - G LOBAL F UNCTIONS (setf func_name) (defun primo (lst) (car lst)) (defun (setf primo) (val lst) (setf (car lst) val)) > (let ((x (list ‘a ‘b ‘c))) (setf (primo x) 480) x) (480 B C) The first parameter : new value The remaining parameters : the arguments of this setf function

F UNCTIONS - G LOBAL F UNCTIONS Documentation string If you make a string the first expression in the body of a function defined with defun, then this string will become the function’s documentation string (defun foo (x) “Implements an enhanced paradigm of diversity.” x) > (documentation ‘foo ‘function) “Implements an enhanced paradigm of diversity.”

F UNCTIONS - L OCAL F UNCTIONS Functions defined via defun or setf of symbol-function are global functions You can access global functions anywhere Local functions can be defined with labels, which is a kind of let for functions (labels ((add10 (x) (+ x 10)) (consa (x) (cons ‘a x))) (consa (add10 3))) (A. 13)

F UNCTIONS - L OCAL F UNCTIONS > (labels ((len (lst) (if (null lst) 0 (+ (len (cdr lst)) 1)))) (len ‘(a b c))) 3

F UNCTIONS - P ARAMETER L ISTS &rest Insert &rest before the last variable in the parameter list of a function This variable will be set to a list of all the remaining arguments (defun our-funcall (fn &rest args) (apply fn args))

F UNCTIONS - P ARAMETER L ISTS &optional All the arguments after it could be omitted (defun philosoph (thing &optional property) (list thing ‘is property)) > (philosoph ‘death) (DEATH IS NIL) The explicit default of the optional parameter (defun philosoph (thing &optional (property ‘fun)) (list thing ‘is property)) > (philosoph ‘death) (DEATH IS FUN)

F UNCTIONS - P ARAMETER L ISTS &key A keyword parameter is a more flexible kind of optional parameter These parameters will be identified not by their position, but by symbolic tags that precede them > (defun keylist (a &key x y z) (list a x y z)) KEYLIST > (keylist 1 :y 2) (1 NIL 2 NIL) > (keylist 1 :y 3 :x 2) (1 2 3 NIL)

F UNCTIONS – E XAMPLE : U TILITIES > (single? ‘(a)) T → returns true when its argument is a list of one element > (append1 ‘(a b c) ‘d) (A B C D) → adds an element to the end of the list > (map-int #’identify 10) ( ) → returns a list of the results of calling the function on the integers from 0 to n-1

F UNCTIONS – E XAMPLE : U TILITIES > (map-int #’(lambda (x) (random 100)) 10) ( ) > (filter #’(lambda (x) (and (evenp x) (+ x 10))) ‘( ) ( ) → returns all the non-nil values returned by the function as it is applied to the elements of the list > (most #’length ‘((a b) (a b c) (a))) (A B C) → returns the element of a list with 3 the highest score, according to some scoring function

F UNCTIONS – E XAMPLE : U TILITIES (defun single? (lst) (and (consp 1st) (null (cdr lst)))) (defun appendl (1st obj) (append 1st (list obj))) (defun map-int (fn n) (let ((acc nil)) (dotimes (i n) (push (funcall fn i) acc)) (nreverse acc))) (defun filter (fn lst) (let ((acc nil)) (dolist (x lst) (let ((val (funcall fn x))) (if val (push val acc)))) (nreverse acc)))

F UNCTIONS – E XAMPLE : U TILITIES (defun most (fn 1st) (if (null 1st) (values nil nil) (let* ((wins (car lst)) (max (funcall fn wins))) (dolist (obj (cdr lst)) (let ((score (funcall fn obj))) (when (> score max) (setf wins obj max score)))) (values wins max))))

F UNCTIONS – C LOSURES (defun combiner (x) (typecase x (number #’+) (list #’append) (t #’list))) (defun combine (&rest args) (apply (combiner (car args)) args)) > (combine 2 3) 5 > (combine ‘(a b) ‘(c d)) (A B C D)

F UNCTIONS – C LOSURES When a function refers to a variable defined outside it, it is called a free variable Closure A function that refers to a free variable (defun add-to-list (num lst) (mapcar #’(lambda (x) (+ x num)) lst)) num is free (defun make-adder (n) #’(lambda (x) (+ x n))) → returns a function n is free

F UNCTIONS – C LOSURES (setf add3 (make-adder 3)) # > (funcall add3 2) 5 (setf add27 (make-adder 27)) # > (funcall add27 2) 29

F UNCTIONS – C LOSURES Make several closures share variables (let ((counter 0)) (defun reset ( ) (setf counter 0)) (defun stamp ( ) (setf counter (+ counter 1)))) > (list (stamp) (stamp) (reset) (stamp)) ( ) You can do the same thing which a global counter, but this way the counter is protected from unintended references

F UNCTIONS – E XAMPLE : F UNCTION B UILDERS (defun disjoin (fn &rest fns) (if (null fns) fn (let ((disj (apply #’disjoin fns))) #’(lambda (&rest args) (or (apply fn args) (apply disj args))))))

F UNCTIONS – E XAMPLE : F UNCTION B UILDERS (defun conjoin (fn &rest fns) (if (null fns) fn (let ((conj (apply #’conjoin fns))) #’(lambda (&rest args) (and (apply fn args) (apply conj args)))))) (defun curry (fn &rest args) #’(lambda (&rest args2) (apply fn (append args args2)))) (defun rcurry (fn &rest args) #’(lambda (&rest args2) (apply fn (append args2 args)))) (defun always (x) #’(lambda (&rest args) x))

F UNCTIONS – E XAMPLE : F UNCTION B UILDERS > (mapcar (disjoin #’integerp #’symbolp) ‘(a “a” 2 3)) (T NIL T T) > (mapcar (conjoin #’integerp #’oddp) ‘(a “a” 2 3)) (NIL NIL NIL T) > (funcall (curry #’- 3) 2) 1 > (funcall (rcurry #’- 3) 2) -1

F UNCTIONS – R ECURSION Recursion plays a greater role in Lisp than in most other languages Functional programming Recursive algorithms are less likely to involve side-effects Recursive data structure Lisp’s implicit use of pointers makes it easy to have recursively defined data structures The most common is the list: a list is either nil, or a cons whose cdr is a list Elegance Lisp programmers care a great deal about the beauty of their programs Recursive algorithms are often more elegant than their iterative counterparts

F UNCTIONS – R ECURSION To solve a problem using recursion, you have to Show how to solve the problem in the general case by breaking it down into a finite number of similar, but smaller, problems Show how to solve the smallest version of the problem - the base case - by some finite number of operations Finding the length of a proper list In the general case, the length of a proper list is the length of its cdr plus 1 The length of an empty list is 0

F UNCTIONS – R ECURSION member Something is a member of a list if it is the first element, or a member of the cdr Nothing is a member of the empty list copy-tree The copy-tree of a cons is a cons made of the copy-tree of its car, and the copy-tree of its cdr The copy-tree of an atom is itself

F UNCTIONS – R ECURSION The obvious recursive algorithm is not always the most efficient E.g. Fibonacci function 1. Fib(0)=Fib(1)=1 2. Fib(n)=Fib(n-1)+Fib(n-2) (defun fib (n) (if (<= n 1) 1 (+ (fib (- n 1)) (fib (- n 2))))) The recursive version is appallingly inefficient The same computations are done over and over

F UNCTIONS – R ECURSION (defun fib (n) (do ((i n (- i 1)) (f1 1 (+ f1 f2)) (f2 1 f1)) ((<= i 1) f1))) The iterative version is not as clear, but it is far more efficient However, this kind of thing happen very rarely in practice

F UNCTIONS Homework (Due April 14) Use the lambda function and closures to write a function called our-complement that takes a predicate and returns the opposite predicate. For example: > (mapcar (our-complement #’oddp) ‘( )) (NIL T NIL T NIL T)