COP4020 Programmig Laguages Fuctioal Programmig Prof. Robert va Egele
Overview What is fuctioal programmig? Historical origis of fuctioal programmig Fuctioal programmig today Cocepts of fuctioal programmig Fuctioal programmig with Scheme Lear (more by example COP4020 Fall 2016 2
What is Fuctioal Programmig? Fuctioal programmig is a declarative programmig style (programmig paradigm Pro: flow of computatio is declarative, i.e. more implicit Pro: promotes buildig more complex fuctios from other fuctios that serve as buildig blocks (compoet reuse Pro: behavior of fuctios defied by the values of iput argumets oly (o side-effects via global/static variables Cos: fuctio compositio is (cosidered to be stateless Cos: programmers prefer imperative programmig costructs such as statemet sequecig, while fuctioal laguages emphasize fuctio compositio COP4020 Fall 2016 3
Cocepts of Fuctioal Programmig Pure fuctioal programmig defies the outputs of a program purely as a fuctio of the iputs with o otio of iteral state (o side effects A pure fuctio ca be couted o to retur the same output each time we ivoke it with the same iput parameter values No global (statically allocated variables No explicit (poiter assigmets Daglig poiters ad u-iitialized variables caot occur! Example pure fuctioal programmig laguages: Mirada, Haskell, ad Sisal No-pure fuctioal programmig laguages iclude imperative features that cause side effects (e.g. destructive assigmets to global variables or assigmets/chages to lists ad data structures Example: Lisp, Scheme, ad ML COP4020 Fall 2016 4
Fuctioal Laguage Costructs Buildig blocks are fuctios No statemet compositio Fuctio compositio No variable assigmets But: ca use local variables to hold a value assiged oce No loops Recursio List comprehesios i Mirada ad Haskell But: do-loops i Scheme Coditioal flow with if-the-else or argumet patters Fuctioal laguages are statically (Haskell or dyamically (Lisp typed Haskell examples: gcd a b a == b = a a > b = gcd (a-b b a < b = gcd a (b-a fac 0 = 1 fac = * fac (-1 member x [] = false member x (y:xs x == y = true x <> y = member x xs COP4020 Fall 2016 5
Theory ad Origi of Fuctioal Laguages Church's thesis: All models of computatio are equally powerful Turig's model of computatio: Turig machie Readig/writig of values o a ifiite tape by a fiite state machie Church's model of computatio: Lambda Calculus Fuctioal programmig laguages implemet Lambda Calculus Computability theory A program ca be viewed as a costructive proof that some mathematical object with a desired property exists A fuctio is a mappig from iputs to output objects ad computes output objects from appropriate iputs For example, the propositio that every pair of oegative itegers (the iputs has a greatest commo divisor (the output object has a costructive proof implemeted by Euclid's algorithm writte as a "fuctio" COP4020 Fall 2016 6
Impact of Fuctioal Laguages o Laguage Desig Useful features are foud i fuctioal laguages that are ofte missig i procedural laguages or have bee adopted by moder programmig laguages: First-class fuctio values: the ability of fuctios to retur ewly costructed fuctios Higher-order fuctios: fuctios that take other fuctios as iput parameters or retur fuctios Polymorphism: the ability to write fuctios that operate o more tha oe type of data Aggregate costructs for costructig structured objects: the ability to specify a structured object i-lie such as a complete list or record value Garbage collectio COP4020 Fall 2016 7
Fuctioal Programmig Today Sigificat improvemets i theory ad practice of fuctioal programmig have bee made i recet years Strogly typed (with type iferece Modular Sugarig: imperative laguage features that are automatically traslated to fuctioal costructs (e.g. loops by recursio Improved efficiecy Remaiig obstacles to fuctioal programmig: Social: most programmers are traied i imperative programmig ad are t used to thik i terms of fuctio compositio Commercial: ot may libraries, ot very portable, ad o IDEs COP4020 Fall 2016 8
Applicatios May (commercial applicatios are built with fuctioal programmig laguages based o the ability to maipulate symbolic data more easily Examples: Computer algebra (e.g. Reduce system Natural laguage processig Artificial itelligece Automatic theorem provig Algorithmic optimizatio of fuctioal programs COP4020 Fall 2016 9
LISP ad Scheme The origial fuctioal laguage ad implemetatio of Lambda Calculus Lisp ad dialects (Scheme, commo Lisp are still the most widely used fuctioal laguages Simple ad elegat desig of Lisp: Homogeeity of programs ad data: a Lisp program is a list ad ca be maipulated i Lisp as a list Self-defiitio: a Lisp iterpreter ca be writte i Lisp Iteractive: user iteractio via "read-eval-prit" loop COP4020 Fall 2016 10
Scheme Scheme is a popular Lisp dialect Lisp ad Scheme adopt a form of prefix otatio called Cambridge Polish otatio Scheme is case isesitive A Scheme expressio is composed of Atoms, e.g. a literal umber, strig, or idetifier ame, Lists, e.g. '(a b c Fuctio ivocatios writte i list otatio: the first list elemet is the fuctio (or operator followed by the argumets to which it is applied: (fuctio arg 1 arg 2 arg 3... arg For example, si(x*x+1 is writte as (si (+ (* x x 1 COP4020 Fall 2016 11
Read-Eval-Prit The "Read-eval-prit" loop provides user iteractio i Scheme A expressio is read, evaluated, ad the result prited Iput: 9 Output: 9 Iput: (+ 3 4 Output: 7 Iput: (+ (* 2 3 1 Output: 7 User ca load a program from a file with the load fuctio (load "my_scheme_program" Note: a file should use the.scm extesio COP4020 Fall 2016 12
Workig with Data Structures A expressio operates o values ad compoud data structures built from atoms ad lists A value is either a atom or a compoud list Atoms are Numbers, e.g. 7 ad 3.14 Strigs, e.g. "abc" Boolea values #t (true ad #f (false Symbols, which are idetifiers escaped with a sigle quote, e.g. 'y The empty list ( Whe eterig a list as a literal value, escape it with a sigle quote Without the quote it is a fuctio ivocatio! For example, '(a b c is a list while (a b c is a fuctio applicatio Lists ca be ested ad may cotai ay value, e.g. '(1 (a b ''s'' COP4020 Fall 2016 13
Checkig the Type of a Value The type of a value ca be checked with (boolea? x ; is x a Boolea? (char? x ; is x a character? (strig? x ; is x a strig? (symbol? x ; is x a symbol? (umber? x ; is x a umber? (list? x ; is x a list? (pair? x ; is x a o-empty list? (ull? x ; is x a empty list? Examples (list? '(2 #t (umber? ''abc'' #f Portability ote: o some systems false (#f is replaced with ( COP4020 Fall 2016 14
Workig with Lists (car xs returs the head (first elemet of list xs (cdr xs (proouced "coulder" returs the tail of list xs (cos x xs jois a elemet x ad a list xs to costruct a ew list (list x 1 x 2 x geerates a list from its argumets Examples: (car '(2 3 4 2 (car '(2 2 (car '( Error (cdr '(2 3 (3 (car (cdr '(2 3 4 3 ; also abbreviated as (cadr '(2 3 4 (cdr (cdr '(2 3 4 (4 ; also abbreviated as (cddr '(2 3 4 (cdr '(2 ( (cos 2 '(3 (2 3 (cos 2 '(3 4 (2 3 4 (list 1 2 3 (1 2 3 COP4020 Fall 2016 15
The if Special Form Special forms resemble fuctios but have special evaluatio rules Evaluatio of argumets depeds o the special costruct The if special form returs the value of theexpr or elseexpr depedig o a coditio (if coditio theexpr elseexpr Examples (if #t 1 2 1 (if #f 1 "a" "a" (if (strig? "s" (+ 1 2 4 3 (if (> 1 2 "yes" "o" "o" COP4020 Fall 2016 16
The cod Special Form A more geeral if-the-else ca be writte usig the cod special form that takes a sequece of (coditio value pairs ad returs the first value x i for which coditio c i is true: (cod (c 1 x 1 (c 2 x 2 (else x Examples (cod (#f 1 (#t 2 (#t 3 2 (cod ((< 1 2 ''oe'' ((>= 1 2 ''two'' ''oe'' (cod ((< 2 1 1 ((= 2 1 2 (else 3 3 Note: else is used to retur a default value COP4020 Fall 2016 17
Logical Expressios Relatios Numeric compariso operators <, <=, =, >, >= Boolea operators (ad x 1 x 2 x, (or x 1 x 2 x Other test operators (zero? x, (odd? x, (eve? x (eq? x 1 x 2 tests whether x 1 ad x 2 refer to the same object (eq? 'a 'a #t (eq? '(a b '(a b #f (equal? x 1 x 2 tests whether x 1 ad x 2 are structurally equivalet (equal? 'a 'a #t (equal? '(a b '(a b #t (member x xs returs the sublist of xs that starts with x, or returs ( (member 5 '(a b ( (member 5 '(1 2 3 4 5 6 (5 6 COP4020 Fall 2016 18
Lambda Calculus: Fuctios = Lambda Abstractios A lambda abstractio is a ameless fuctio (a mappig specified with the lambda special form: (lambda args body where args is a list of formal argumets ad body is a expressio that returs the result of the fuctio evaluatio whe applied to actual argumets A lambda expressio is a uevaluated fuctio Examples: (lambda (x (+ x 1 (lambda (x (* x x (lambda (a b (sqrt (+ (* a a (* b b COP4020 Fall 2016 19
Lambda Calculus: Ivocatio = Beta Reductio A lambda abstractio is applied to actual argumets usig the familiar list otatio (fuctio arg 1 arg 2... arg where fuctio is the ame of a fuctio or a lambda abstractio Beta reductio is the process of replacig formal argumets i the lambda abstractio s body with actuals Examples ( (lambda (x (* x x 3 (* 3 3 9 ( (lambda (f a (f (f a (lambda (x (* x x 3 (f (f 3 where f = (lambda (x (* x x (f ( (lambda (x (* x x 3 where f = (lambda (x (* x x (f 9 where f = (lambda (x (* x x ( (lambda (x (* x x 9 (* 9 9 81 COP4020 Fall 2016 20
Defiig Global Names A global ame is defied with the defie special form (defie ame value Usually the values are fuctios (lambda abstractios Examples: (defie my-ame ''foo'' (defie determiers '(''a'' ''a'' ''the'' (defie sqr (lambda (x (* x x (defie twice (lambda (f a (f (f a (twice sqr 3 ((lambda (f a (f (f a (lambda (x (* x x 3 ((lambda (x (* x x ((lambda (x (* x x 3 ((lambda (x (* x x (* 3 3 (* 9 9 81 COP4020 Fall 2016 21
Usig Local Names The let special form (let-expressio provides a scope costruct for local ame-to-value bidigs (let ( (ame 1 x 1 (ame 2 x 2 (ame x expressio where ame 1, ame 2,, ame i expressio are substituted by x 1, x 2,, x Examples (let ( (plus + (two 2 (plus two two 4 (let ( (a 3 (b 4 (sqrt (+ (* a a (* b b 5 (let ( (sqr (lambda (x (* x x (sqrt (+ (sqr 3 (sqr 4 5 COP4020 Fall 2016 22
Local Bidigs with Self Refereces A global ame ca simply refer to itself (for recursio (defie fac (lambda ( (if (zero? 1 (* (fac (- 1 A let-expressio caot refer to its ow defiitios Its defiitios are ot i scope, oly outer defiitios are visible Use the letrec special form for recursive local defiitios (letrec ( (ame 1 x 1 (ame 2 x 2 (ame x expr where ame i i expr refers to x i Examples (letrec ( (fac (lambda ( (if (zero? 1 (* (fac (- 1 (fac 5 120 COP4020 Fall 2016 23
I/O (display x prits value of x ad returs a uspecified value (display "Hello World!" Displays: "Hello World!" (display (+ 2 3 Displays: 5 (ewlie advaces to a ew lie (read returs a value from stadard iput (if (member (read '(6 3 5 9 "You guessed it!" "No luck" Eter: 5 Displays: You guessed it! COP4020 Fall 2016 24
Blocks (begi x 1 x 2 x sequeces a series of expressios x i, evaluates them, ad returs the value of the last oe x Examples: (begi (display "Hello World!" (ewlie (let ( (x 1 (y (read (plus + (begi (display (plus x y (ewlie COP4020 Fall 2016 25
Do-loops The do special form takes a list of triples ad a tuple with a termiatig coditio ad retur value, ad multiple expressios x i to be evaluated i the loop (do (triples (coditio ret-expr x 1 x 2 x Each triple cotais the ame of a iterator, its iitial value, ad the update value of the iterator Example (displays values 0 to 9 (do ( (i 0 (+ i 1 ( (>= i 10 "doe" (display i (ewlie COP4020 Fall 2016 26
Higher-Order Fuctios A fuctio is a higher-order fuctio (also called a fuctioal form if It takes a fuctio as a argumet, or It returs a ewly costructed fuctio as a result For example, a fuctio that applies a fuctio to a argumet twice is a higher-order fuctio (defie twice (lambda (f a (f (f a Scheme has several built-i higher-order fuctios (apply f xs takes a fuctio f ad a list xs ad applies f to the elemets of the list as its argumets (apply '+ '(3 4 7 (apply (lambda (x (* x x '(3 (map f xs takes a fuctio f ad a list xs ad returs a list with the fuctio applied to each elemet of xs (map odd? '(1 2 3 4 (#t #f #t #f (map (lambda (x (* x x '(1 2 3 4 (1 4 9 16 COP4020 Fall 2016 27
No-Pure Costructs Assigmets are cosidered o-pure i fuctioal programmig because they ca chage the global state of the program ad possibly ifluece fuctio outcomes The value of a pure fuctio oly depeds o its argumets (set! ame x re-assigs x to local or global ame (defie a 0 (set! a 1 ; overwrite with 1 (let ( (a 0 (begi (set! a (+ a 1 ; icremet a by 1 (display a ; shows 1 (set-car! x xs overwrites the head of a list xs with x (set-cdr! xs ys overwrites the tail of a list xs with ys COP4020 Fall 2016 28
Example 1 Recursive factorial: (defie fact (lambda ( (if (zero? 1 (* (fact (- 1 (fact 2 (if (zero? 2 1 (* 2 (fact (- 2 1 (* 2 (fact 1 (* 2 (if (zero? 1 1 (* 1 (fact (- 1 1 (* 2 (* 1 (fact 0 (* 2 (* 1 (if (zero? 0 1 (* 0 (fact (- 0 1 (* 2 (* 1 1 2 COP4020 Fall 2016 29
Example 2 Iterative factorial (defie iterfact (lambda ( (do ( (i 1 (+ i 1 ; i rus from 1 updated by 1 (f 1 (* f i ; f from 1, multiplied by i ( (> i f ; util i >, retur f ; loop body is omitted COP4020 Fall 2016 30
Example 3 Sum the elemets of a list (defie sum (lambda (lst (if (ull? lst 0 (+ (car lst (sum (cdr lst (sum '(1 2 3 (+ 1 (sum (2 3 (+ 1 (+ 2 (sum (3 (+ 1 (+ 2 (+ 3 (sum ( (+ 1 (+ 2 (+ 3 0 COP4020 Fall 2016 31
Example 4 Geerate a list of copies of x (defie fill (lambda ( x (if (= 0 ( (cos x (fill (- 1 x (fill 2 'a (cos a (fill 1 a (cos a (cos a (fill 0 a (cos a (cos a ( (a a COP4020 Fall 2016 32
Example 5 Replace x with y i list xs (defie subst (lambda (x y xs (cod ((ull? xs ( ((eq? (car xs x (cos y (subst x y (cdr xs (else (cos (car xs (subst x y (cdr xs (subst 3 0 '(8 2 3 4 3 5 '(8 2 0 4 0 5 COP4020 Fall 2016 33
Example 6 Higher-order reductios (defie reduce (lambda (op xs (if (ull? (cdr xs (car xs (op (car xs (reduce op (cdr xs (reduce ad '(#t #t #f (ad #t (ad #t #f #f (reduce * '(1 2 3 (* 1 (* 2 3 6 (reduce + '(1 2 3 (+ 1 (+ 2 3 6 COP4020 Fall 2016 34
Example 7 Higher-order filter operatio: keep elemets of a list for which a coditio is true (defie filter (lambda (op xs (cod ((ull? xs ( ((op (car xs (cos (car xs (filter op (cdr xs (else (filter op (cdr xs (filter odd? '(1 2 3 4 5 (1 3 5 (filter (lambda ( (<> 0 '(0 1 2 3 4 (1 2 3 4 COP4020 Fall 2016 35
Example 8 Biary tree isertio, where ( are leaves ad (val left right is a ode (defie isert (lambda ( T (cod ((ull? T (list ( ( ((= (car T T ((> (car T (list (car T (isert (cadr T (caddr T ((< (car T (list (car T (cadr T (isert (caddr T (isert 1 '(3 ( (4 ( ( (3 (1 ( ( (4 ( ( COP4020 Fall 2016 36
Haskell A lazy fuctioal laguage with a static type system Lazy: evaluates expressios o demad, i.e. operads ad argumets are ot evaluated util used i the fuctio body Static type iferece: types are automatically iferred to verify expressios Polymorphic types Type variables, e.g. * i hd:: [*] -> * Higher-order fuctios Fuctios that take fuctios as argumets or retur fuctios Modular Compiled COP4020 Fall 2016 37
Haskell Sytax Sytax of fuctio ivocatio: fuctioame arg 1 arg 2 arg 3 Note: parethesis oly eeded for ested calls, e.g. hd (tl xs Fuctio defiitio fuctioame arg 1 arg 2 arg 3 = expressio Fuctio defiitio with guards fuctioame arg 1 arg 2 arg 3 guard 1 = expressio 1 guard 2 = expressio 2 Lambda abstractio otatio: \ arg -> expressio COP4020 Fall 2016 38
Haskell Sytax Lists ad primitive list operatios [e 1, e 2, e 3 ] e 1 : [e 2, e 3 ] evaluates to [e 1, e 2, e 3 ] hd [e 1, e 2, e 3 ] evaluates to e 1 tl [e 1, e 2, e 3 ] evaluates to [e 2, e 3 ] Commo list operatios legth [e 1, e 2, e 3 ] evaluates to 3 map f [e 1, e 2, e 3 ] evaluates to [f e 1, f e 2, f e 3 ] foldl! z [e 1, e 2, e 3 ] evaluates to ((z!e 1!e 2!e 3 foldr! z [e 1, e 2, e 3 ] evaluates to e 1!(e 2!(e 3!zfilter p [e 1, e 2, e 3 ] evaluates to list of e i whe p e i is true COP4020 Fall 2016 39
Haskell by Example -- 1 usig if-the-else coditioal expressios factorial = if > 0 the * factorial (-1 else 1 -- 2 usig argumet patter matchig factorial 0 = 1 factorial = * factorial (-1 -- 3 usig a guard factorial 0 = 1 factorial > 0 = * factorial (-1 -- type of the factorial fuctio factorial :: Iteger -> Iteger COP4020 Fall 2016 40
Haskell by Example (cot d -- 1 list legth usig argumet patter legth [] = 0 legth (x:xs = 1 + legth xs -- 2 usig where legth [] = 0 legth (x:xs = 1 + rest where rest = legth xs -- 3 usig let legth [] = 0 legth (x:xs = { let rest = legth xs } i 1 + rest -- type of the legth fuctio (polymorphic legth :: [*] -> Iteger COP4020 Fall 2016 41
Haskell by Example (cot d -- usig Curryig, which gives: ic x = add 1 x add a b = a + b ic = add 1 -- 1 higher-order, apply fuctio to each list elemet plus1 xs = map ic xs -- 2 usig Curryig plus1 = map ic COP4020 Fall 2016 42