functional programming spring 2008

42
Functional Programming Spring 2008 Yu-Tzu Lin ( 林林林 ) http://web.ntnu.edu.tw/~linyt

Upload: chandler

Post on 22-Feb-2016

28 views

Category:

Documents


0 download

DESCRIPTION

Functional Programming Spring 2008. Yu-Tzu Lin ( 林育慈 ) http://web.ntnu.edu.tw/~linyt. Information. Time and Place Classroom: Room 801, Information and Technology Center Time: Monday 13:10-16:00 TA and TA hours: 顏百璋 Free resources - PowerPoint PPT Presentation

TRANSCRIPT

Functional Programming

Functional ProgrammingSpring 2008

Yu-Tzu Lin ()http://web.ntnu.edu.tw/~linytInformationTime and Place Classroom: Room 801, Information and Technology CenterTime: Monday 13:10-16:00TA and TA hours: Free resourcesCommon Lisp the Language, 2nd edition by Guy L. Steele, Thinking Machines, Inc. , Digital Press, 1990.http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node1.htmlhttp://web.ntnu.edu.tw/~linyt/func_prog/cltl_ps.tarPractical Common LISP, by Peter Seibel, Apress/Springer-Verlag New York Inc , 2005.(Not suitable for a beginner, but has a free web version)http://www.gigamonkeys.com/book/http://www.lispworks.com/documentation/HyperSpec/Front/index.htm (A reference manual)http://www.lisp.org/table/references.htm#cltl2

2

Information (cont.)ReferencesANSI Common LISP, by Paul Graham, Prentice Hall, 1995. (A good introductory book)LISP, by Patrick Henry Winston and Bertbold Klaus Paul Horn, Addison Wesley, 1989.(A quick guide to write Lisp)Introduction to functional programming, by Richard Bird and Philip Wadler, Prentice-Hall , 1988.Functional programming, by Jeroen Fokker, 1995. (Free for educational purposes)

3Information (cont.)GradeHomework: 30%Midterm exam: 30%Final project: 40%

"I can do everything through him who gives me strength Phillipians 4:13

4SyllabusIntroductionListsSpecialized Data StructuresControlFunctionsInput and outputSymbolsNumbersMacrosStructure

5Introduction-Functional ProgrammingComputers are expensive in early days make the programming language resemble the computer architecture imperative programminge.g. Pascal, C,

Statement 1;Statement 2;Statement 3;Statement n;6Introduction-Functional ProgrammingThere were already methods to solve problems before the invention of computersFunctions play a much more central rolesFunctionExpresses the connection between parameters (input) and the result (output)Is a good way of specifying a computation

7InputOutputFunctionResult=f(parameter 1, parameter 2, , parameter p)Introduction-Functional ProgrammingA functional program consists of the definition of one or more functions8Function 1Function 2Function 3Function nIntroduction-LispLisp was first conceived by John McCarthy in 1956The first functional programming languageNot the language satisfies all modern demandsOther functional programming languages came to existence for different purposesMLScheme (an adjustment to Lisp)HaskellDesigned to evolveYou can use Lisp to define new lisp operators

9Introduction-LispExample

10; Lisp /* C */(defun sum (n) int sum(int n){ (let ((s 0)) int i, s = 0; (dotimes (i n s) for (i = 0; i < n; i++) (incf s i ) ) ) ) s += i; return(s); }Introduction-LispStart to writeCLISPhttp://web.ntnu.edu.tw/~linyt/func_prog/CLisp.ziphttp://web.ntnu.edu.tw/~linyt/func_prog/cltl_ps.tarhttp://joung.im.ntu.edu.tw/teaching/pl/2001/Common_Lisp/readme.html

11Introduction-LispAn interactive front-end (toplevel)> is the toplevel prompt> 1 (you type 1)1 (the system print its value evaluate to itself)> (another prompt to say that its ready for more)> (+ 2 3)5+ is the operatorThe numbers 2 and 3 are argumentsPrefix notation2 + 3 + 4?

12Introduction-Lisp> (+)0> (+ 2)2> (+ 2 3)5> (+ 2 3 4 5)1413Introduction-Atoms and ListsExpressions can be nested> (/ (-7 1) (- 4 2))?Lisp uses a single notation to express all ideasAtomList

14Introduction-Evaluation(+ 2 3)+ is a function2 and 3 are arguments(+ 2 3) is a function callFunction evaluation1: the arguments are evaluated, from left to right2: the values of the arguments are passed to the function named by the operator15Introduction-Evaluation(/ (- 7 1) (- 4 2))1: evaluate (- 7 1)1.1: evaluate 71.2: evaluate 11.3: pass 7 and 1 to the function -, which returns 62: evaluate (- 4 2)2.1: evaluate 42.2: evaluate 22.3: pass 4 and 2 to the function -, which returns 23: pass 6 and 2 to the function /, which returns 3

16Introduction-Evaluation> (/ 1 0)Error: Division by zero.> (quote (+ 3 5))(+ 3 5)> (+ 3 5)(+ 3 5)Quote takes a single argument and just returns it verbatimA way to protect expressions from evaluation17Introduction-DataLisp offers all the data types we find in most other languagesInteger e.g. 256String e.g ora et laboraSpecial data typeSymbolWordListIs represented zero or more elements enclosed in parentheses

18Introduction-DataSymbolDoes not evaluate to itselfIf you want to refer to a symbol, you should quote it> ArtichokeARTICHOKEListThe elements can be of any type, including listsYou have to quote lists, or lisp would take them for functions calls> (my 3 Sons)(MY 3 Sons)> (the list (a b c) has 3 elements)(THE LIST (a b c) HAS 3 ELEMENTS)One quote protects a whole expression19Introduction-DataBuild lists by calling list> (list my (+ 2 1) Sons)(MY 3 Sons)The list is evaluated to returnThe list itself if it is quotedIts value if it is not quoted> (list (+ 2 1) (+ 2 1))((+ 2 1) 3)Lisp programs are expressed as listsYou can write programs to generate programs20Introduction-DataEmpty list> ( )NILnilNILYou dont have to quote nil because nil evaluates to itself21Introduction-List OperatorsCons(cons )> (cons a (b c d))(A B C D)> (cons a (cons b nil))(A B)> (list a b)(A B)22Introduction-List OperatorsFirst> (first (fast computers are nice))FASTRest> (rest (fast computers are nice))(COMPUTERS ARE NICE)Car> (car (a b c))A> (cdr (a b c))(B C)> (car (cdr (cdr (a b c d))))CCxxxxrx is a or d23Introduction-TruthThe symbol t is the default representation for truthLike nil, t evaluates to itself(listp object)Returns true when object is a list> (listp (a b c))T> (listp 27)NILA function whose return value is intended to be interpreted as truth or falsity is called a predicateCommon Lisp predicates often have names that end with p24Introduction-Truth(null object)Returns true when object is nil> (null nil)T(not object)Returns true when object is nil> (not nil)T

25Introduction-Truth> (if (listp (a b c)) (+ 1 2) (+ 5 6))3> (if (listp 27) (+ 1 2) (+ 5 6))11> (if (listp 27) (+ 2 3))NIL> (if 27 1 2)1Everything except nil also counts as true26Introduction-Truth(and expression)Evaluates the expression in order, returning nil immediately if one evaluates to nil, or if they all return true, the value of the last. Returns t if given no arguments.> (and t (+ 1 2))3

27IntroductionExercisesDescribe what happens when the following expressions are evaluated(+ (- 5 1) (+ 3 7))(list 1 (+ 2 3))(if (listp 1) (+ 1 2) (+ 3 4))(list (and (listp 3) t) (+ 1 2))28Introduction-Functionsdefun> (defun our-fun (x) (car (cdr (cdr x))))OUR-FUN> (our-fun (a b c d))CA symbol has to be quoted because otherwise it will be treated as a variable> (> (+ 1 4) 3)T(defun sum-greater (x y z) (> (+ x y) z))SUM-GREATER > (sum-greater 1 4 3)T29Introduction-FunctionsLisp makes no distinction between a program, a procedure, and a functionFunctions do for everything30Introduction-Recursion(defun our-member (obj lst) (if (null lst) nil (if (eql (car lst) obj) lst (our-member obj (cdr lst)))))> (our-member b (a b c))(B C)> (our-member z (a b c))NIL31Introduction-Input and Output> (format t ~A plus ~A equals ~A. ~% 2 3 (+ 2 3 ))2 plus 3 equals 5.NILThe first line is displayed by formatThe second line is the value returned by the call to formatt indicates that the output is to be sent to standard outputThe second argument is a string that serves as a template for output~% indicates a newline32Introduction-Input and OutputReadNo argumentsReads from the standard input (toplevel)(defun ask (string) (format t ~A string) (read))> (ask How old are you?)How old are you? 202033Introduction-VariablesLetOne of the most frequently used operators in Common Lisp> (let ((x 1) (y 2)) (+ x y))3(defun ask-number ( ) (format t Please enter a number. ) (let ((val (read))) (if (numberp val) val (ask-number))))34Introduction-VariablesGlobal variable> (defparameter *x* 32)*x*> *x*32(defconstant limit (+ *x* 1))(boundp symbol)Returns true iff symbol is the name of a special variable> (boundp *x*)T35IntroductionExercisesWhat does this function do?(defun enigma (x) (and (not (null x)) (or (null (car x)) (enigma (cdr x))))) 36Introduction-Assignment> (setf *x* 98)98> (let ((n 10) (setf n 2) n)2> (setf x (list a b c))(A B C)> (setf (car x ) n)N> x(N B C)37Introduction-Assignment(setf a b c d e f)(setf a b)(setf c d)(setf e f)38Introduction-Functional programming in LispFunctional programming means writing programs that work by returning values, instead of by modifying things> (setf lst (c a r a t))(C A R A T)> (remove a lst)(C R T)> lst(C A R A T)(setf new_x (remove a x))39Introduction-Iteration(defun show-squares (start end) (do ((i start (+ i 1))) ((> i end) done) (format t ~A ~A~% i (* i i))))> (show-squares 2 5)2 43 94 165 25DONE40Introduction-Functions as ObjectsIn Lisp, functions are regular objects, like symbols or strings or lists(function function_name)Returns the function whose name is function_name> (function +)#> # +> (apply #+ (1 2 3))6> (+ 1 2 3)641IntroductionExercisesMary is trying to write a function that returns the sum of all the non-nil elements in a list. Explain why this program cannot give a correct answer.(defun summit (lst) (remove nil lst) (apply #+ lst))42