430 likes | 562 Views
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
E N D
Functional ProgrammingSpring 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 • Common 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.html • http://web.ntnu.edu.tw/~linyt/func_prog/cltl_ps.tar • Practical 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
Information (cont.) • References • ANSI 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)
Information (cont.) • Grade • Homework: 30% • Midterm exam: 30% • Final project: 40% "I can do everything through him who gives me strength“ Phillipians 4:13
Syllabus • Introduction • Lists • Specialized Data Structures • Control • Functions • Input and output • Symbols • Numbers • Macros • Structure
Introduction-Functional Programming • Computers 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;
Introduction-Functional Programming • There were already methods to solve problems before the invention of computers • Functions play a much more central roles • Function • Expresses the connection between parameters (input) and the result (output) • Is a good way of specifying a computation Function Input Output Result=f(parameter 1, parameter 2, …, parameter p)
Introduction-Functional Programming • Afunctional program consists of the definition of one or more functions Function 1 Function 2 Function 3 … Function n
Introduction-Lisp • Lisp was first conceived by John McCarthy in 1956 • The first functional programming language • Not the language satisfies all modern demands • Other functional programming languages came to existence for different purposes • ML • Scheme (an adjustment to Lisp) • Haskell • … • Designed to evolve • You can use Lisp to define new lisp operators
Introduction-Lisp • Example ; Lisp /* C */ (defun sum (n) int sum(int n){ (let ((s 0)) inti, s = 0; (dotimes (i n s) for (i = 0; i < n; i++) (incf s i ) ) ) ) s += i; return(s); }
Introduction-Lisp • Start to write • CLISP • http://web.ntnu.edu.tw/~linyt/func_prog/CLisp.zip • http://web.ntnu.edu.tw/~linyt/func_prog/cltl_ps.tar • 中文用法http://joung.im.ntu.edu.tw/teaching/pl/2001/Common_Lisp/readme.html
Introduction-Lisp • An 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 it’s ready for more) • > (+ 2 3)5 • + is the operator • The numbers 2 and 3 are arguments • Prefix notation • 2 + 3 + 4?
Introduction-Lisp • > (+)0 • > (+ 2)2 • > (+ 2 3)5 • > (+ 2 3 4 5)14
Introduction-Atoms and Lists • Expressions can be nested> (/ (-7 1) (- 4 2))? • Lisp uses a single notation to express all ideas • Atom • List
Introduction-Evaluation • (+ 2 3) • + is a function • 2 and 3 are arguments • (+ 2 3) is a function call • Function evaluation • 1: the arguments are evaluated, from left to right • 2: the values of the arguments are passed to the function named by the operator
Introduction-Evaluation • (/ (- 7 1) (- 4 2)) • 1: evaluate (- 7 1) • 1.1: evaluate 7 • 1.2: evaluate 1 • 1.3: pass 7 and 1 to the function -, which returns 6 • 2: evaluate (- 4 2) • 2.1: evaluate 4 • 2.2: evaluate 2 • 2.3: pass 4 and 2 to the function -, which returns 2 • 3: pass 6 and 2 to the function /, which returns 3
Introduction-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 verbatim • A way to protect expressions from evaluation
Introduction-Data • Lisp offers all the data types we find in most other languages • Integer e.g. 256 • String e.g “ora et labora” • … • Special data type • Symbol • Word • List • Is represented zero or more elements enclosed in parentheses
Introduction-Data • Symbol • Does not evaluate to itself • If you want to refer to a symbol, you should quote it • > ‘ArtichokeARTICHOKE • List • The elements can be of any type, including lists • You 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 expression
Introduction-Data • Build lists by calling list • > (list ‘my (+ 2 1) “Sons”)(MY 3 “Sons”) • The list is evaluated to return • The list itself if it is quoted • Its value if it is not quoted • > (list ‘(+ 2 1) (+ 2 1))((+ 2 1) 3) • Lisp programs are expressed as lists • You can write programs to generate programs
Introduction-Data • Empty list • > ( )NIL • nilNIL • You don’t have to quote nil because nil evaluates to itself
Introduction-List Operators • Cons • (cons <new first element> <a list>) • > (cons ‘a ‘(b c d))(A B C D) • > (cons ‘a (cons ‘b nil))(A B) • > (list ‘a ‘b)(A B)
Introduction-List Operators • First • > (first ‘(fast computers are nice))FAST • Rest • > (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)))) • C • Cxxxxr • x is a or d
Introduction-Truth • The symbol t is the default representation for truth • Like nil, t evaluates to itself • (listpobject) • Returns true when object is a list • > (listp ‘(a b c))T • > (listp 27)NIL • A function whose return value is intended to be interpreted as truth or falsity is called a predicate • Common Lisp predicates often have names that end with p
Introduction-Truth • (null object) • Returns true when object is nil • > (null nil)T • (not object) • Returns true when object is nil • > (not nil)T
Introduction-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)1 • Everything except nil also counts as true
Introduction-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
Introduction • Exercises • Describe 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))
Introduction-Functions • defun • > (defun our-fun (x) (car (cdr (cdr x))))OUR-FUN • > (our-fun ‘(a b c d))C • A 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)T
Introduction-Functions • Lisp makes no distinction between a program, a procedure, and a function • Functions do for everything
Introduction-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))NIL
Introduction-Input and Output • > (format t “~A plus ~A equals ~A. ~%” 2 3 (+ 2 3 ))2 plus 3 equals 5.NIL • The first line is displayed by format • The second line is the value returned by the call to format • t indicates that the output is to be sent to standard output • The second argument is a string that serves as a template for output • ~% indicates a newline
Introduction-Input and Output • Read • No arguments • Reads from the standard input (toplevel) • (defun ask (string) (format t “~A” string) (read)) • > (ask “How old are you?”)How old are you? 2020
Introduction-Variables • Let • One 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))))
Introduction-Variables • Global 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*)T
Introduction • Exercises • What does this function do?(defun enigma (x) (and (not (null x)) (or (null (car x)) (enigma (cdr x)))))
Introduction-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)
Introduction-Assignment • (setf a b c d e f) • (setf a b)(setf c d)(setf e f)
Introduction-Functional programming in Lisp • Functional 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))
Introduction-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 25DONE
Introduction-Functions as Objects • In Lisp, functions are regular objects, like symbols or strings or lists • (function function_name) • Returns the function whose name is function_name • > (function +)#<SYSTEM-FUNCTION + > • > #’ + • > (apply #’+ ‘(1 2 3))6 • > (+ 1 2 3)6
Introduction • Exercises • Mary 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))