cs 2104 – prog. lang. concepts functional programming ii
DESCRIPTION
CS 2104 – Prog. Lang. Concepts Functional Programming II. Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes. +. :. 1. +. 2. :. 1. +. 4. :. 1. 0. 6. []. reduce ( op *) [2,4,6] 1 ==> 2 * (4 * (6 * 1)) ==> 48. - PowerPoint PPT PresentationTRANSCRIPT
![Page 1: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/1.jpg)
CS 2104 – Prog. Lang. ConceptsFunctional Programming II
Lecturer : Dr. Abhik Roychoudhury
School of ComputingFrom Dr. Khoo Siau Cheng’s lecture notes
![Page 2: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/2.jpg)
reduce (op *) [2,4,6] 1 ==> 2 * (4 * (6 * 1))==> 48
reduce (fn (x,y)=>1+y) [2,4,6] 0 ==> 1 + (1 + (1 + 0))==> 3
[]
:
2 :
4 :
6
+
1 +
1 +
1 0
![Page 3: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/3.jpg)
Types: Classification of Values and
Their Operators
Type Values Operationsbool true,false =, <>, …int …,~1,0,1,2,… =,<>,<,+,div,…real ..,0.0,.,3.14,.. =,<>,<,+,/,…string “foo”,”\”q\””,… =,<>,…
Basic Types
Boolean Operations: e1 andalso e2 e1 orelse e2
![Page 4: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/4.jpg)
Types in ML
• Every expression used in a program must be well-typed.– It is typable by the ML Type system.
• Declaring a type :3 : int
[1,2] : int list
• Usually, there is no need to declare the type in your program – ML infers it for you.
![Page 5: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/5.jpg)
Structured TypesStructured Types consist of structured values.
• Structured values are built up through expressions. Eg : (2+3, square 3)• Structured types are denoted by type expressions.
<type-expr> ::= <type-name> | <type-constant> | <type-expr> * <type-expr>
| <type-expr> <type-expr> | <type-expr> list
| …
![Page 6: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/6.jpg)
Type of a Tuple
A * B = set of ordered pairs (a,b)
Data Constructor : ( , ) as in (a,b)Type Constructor : * as in A * B
In general,(a1,a2,…,an) belongs to A1*A2*…*An.
(1,2) : int * int(3.14159, x+3,true) : real * int * bool
![Page 7: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/7.jpg)
Type of A List
[1,2,3] : int list [3.14, 2.414] : real list[1, true, 3.14] : ??
Type Constructor : list
A in A-list refers to any types:(int*int) list : [ ], [(1,3)], [(3,3),(2,1)], …int list list : [ ], [[1,2]], [[1],[0,1,2],[2,3],…
A list = set of all lists of A -typed values.
Not well-typed!!
![Page 8: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/8.jpg)
fac : int -> int
Function TypesDeclaring domain & co-
domain
Type Constructor : ->Data Construction via :1. Function declaration : fun f x = x + 1 ;2. Lambda abstraction : fn x => x + 1;
Value Selection via function application:f 3 4
(fn x => x + 1) 3 4
A -> B = set of all functions from A to B.
![Page 9: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/9.jpg)
datatype Days = Mo | Tu | We | Th | Fr | Sa | Su ;
Selecting a summand via pattern matching:case d of Sa => “Go to cinema” | Su => “Extra Curriculum” | _ => “Life goes on”
Sum of Types Enumerated Types
New Type data / data constructors
![Page 10: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/10.jpg)
Defining an integer binary tree:datatype IntTree = Leaf int |
Node of (IntTree, int, IntTree) ;
fun height (Leaf x) = 0 | height (Node(t1,n,t2))=
1 + max(height(t1),height(t2)) ;
Combining Sum and Product of Types:
Algebraic Data Types
![Page 11: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/11.jpg)
Some remarks
• A functional program consists of an expression, not a sequence of statements.
• Higher-order functions are first-class citizen in the language.– It can be nameless
• List processing is convenient and expressive• In ML, every expression must be well-typed.• Algebraic data types empowers the language.
![Page 12: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/12.jpg)
Outline
• More about Higher-order Function
• Type inference and Polymorphism
• Evaluation Strategies
• Exception Handling
![Page 13: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/13.jpg)
Function with Multiple Arguments
• Curried functions accept multiple arguments
fun twice f x = f (f x) ;
Take 2 arguments
Apply 1st argument
Apply 2nd argument
Curried function enables partial application.
let val inc2 = twice (fn x => x + x)
in (inc2 1) + (inc2 2)
end;
val it = 12 ;
![Page 14: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/14.jpg)
Curried vs. Uncurried
Curried functions fun twice f x = f (f x) ;
twice (fn x => x+x) 3 12
Uncurried functions fun twice’ (f, x) = f (f x) ;
twice’ (fn x => x+x, 3) 12
![Page 15: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/15.jpg)
Curried Functions
Curried functions provide extra flexibilityto the language.
compose f g = fn x => f (g x)
compose f g x = f (g x)
compose f = fn g => fn x => f (g x)
compose = fn f => fn g => fn x => f (g x)
![Page 16: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/16.jpg)
fun f(x,y) = x + yf : int*int -> int
Types of Multi-Argument Funs
fun g x y = x + yg : int -> int -> int
(g 3) : int -> int((g 3) 4) : int
Function application is left associative; -> is right associative
![Page 17: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/17.jpg)
Outline
• More about Higher-order Function
• Type inference and Polymorphism
• Evaluation Strategies
• Exception Handling
![Page 18: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/18.jpg)
Type Inference
• ML expressions seldom need type declaration.• ML cleverly infers types without much help from the user.
2 + 2 ; val it = 4 : int fun succ n = n + 1 ; val succ = fn : int -> int
![Page 19: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/19.jpg)
• Explicit types are needed when type coercion is needed.
fun add(x,y : real) = x + y ;
fun add(x,y) = (x:real) + y;
val add = fn : real*real -> real
Helping the Type Inference
![Page 20: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/20.jpg)
• Conditional expression has the same type at both branch.
fun abs(x) = if x>0 then x else 0-x ; val abs = fn : int -> int
Every Expression has only One Type
fun f x = if x > 0 then x else [1,2,3]val f = fn : Int -> ???
This is not type-able in ML.
![Page 21: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/21.jpg)
Example of Type Inference
fun f g = g (g 1)
type(g) = t = intt2 = t2t3int = t2, t2 = t3
type(g) = t = int inttype(f) = t t1 = t t3
= (int int) int
tt1
tintt2
t2t3
t3
![Page 22: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/22.jpg)
Three Type Inference Rules
(Application rule) If f x : t, then x : t’ and
f : t’ -> t for some new type t’.
(Equality rule) If both the types x : t and x : t’ can be deduced for a variable x, then t = t’.
(Function rule) If t u = t’ u’, then t = t’ and u = u’.
![Page 23: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/23.jpg)
Example of Type Inferencefun f g = g (g 1)
Let g : tg (g (g 1)) : trhs
So, by function declaration, we havef : tg -> trhs
By application rule, let (g 1): t(g 1)
g (g 1) : trhs g : t(g 1) -> trhs.By application rule,
(g 1) : t(g 1) g : int -> t(g 1).
By equality rule : t(g 1)= int = trhs.
By equality rule : tg = int -> intHence, f : (int -> int) -> int
![Page 24: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/24.jpg)
Parametric Polymorphism
fun I x = x ; val I = fn : ’a -> ’a
• A Polymorphic function is one whose type contains type parameters.
Type parameter
(I 3) (I [1,2]) (I square)
• Interpretation of val I = fn : ’a -> ’afor all type ‘a, function I takes an input of type ‘a and returns a result of the same type ‘a.
• A poymorphic function can be applied to arguments of more than one type.
![Page 25: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/25.jpg)
Polymorphic Functions
• A polymorphic function is one whose type contains type parameter.
fun map f [] = []
| map f (x::xs) = (f x) :: (map f xs)
Type of map : (’a->’b) -> [’a] -> [’b]
map (fn x => x+1) [1,2,3] => [2,3,4]
map (fn x => [x]) [1,2,3] => [[1],[2],[3]]
map (fn x => x) [“y”,“n”] => [“y”, “n”]
![Page 26: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/26.jpg)
Examples of Polymorphic Functions
fun compose f g = (fn x => f (g x))
t1t2tt4t5t4
t5t6
t4t6type(f) = t1 = t5t6type(g) = t2 = t4t5range(compose) = t = t4t6type(compose) = t1t2t
= (t5t6) (t4t5) (t4t6)
![Page 27: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/27.jpg)
Examples of Polymorphic Functions
fun compose f g = (fn x => f (g x))
Let x:tx f:tf g:tg so compose: tf -> tg ->trhs
(fn x=>f (g x)):trhs => trhs = tx->t(f(gx))
(g x):t(gx) ==> g: tx->t(gx) and tg = tx->t(g x)
(f (g x)):t(f(gx)) ==> f:t(gx)->t(f(gx)) and tf = t(gx)->t(f(gx))
compose: (t(gx)->t(f(gx)))->(tx->t(gx))->(tx->t(f(gx)))Rename the variables:compose: (’a->’b)->(’c->’a)->(’c->’b)
![Page 28: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/28.jpg)
Outline
• More about Higher-order Function
• Type inference and Polymorphism
• Evaluation Strategies
• Exception Handling
![Page 29: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/29.jpg)
Approaches to Expression Evaluation
• Different approaches to evaluating an expression may change the expressiveness of a programming language.
• Two basic approaches:– Innermost (Strict) Evaluation Strategy
• SML, Scheme
– Outermost (Lazy) Evaluation Strategy• Haskell, Miranda, Lazy ML
![Page 30: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/30.jpg)
Innermost Evaluation Strategy
• To Evaluate the call <name><actuals> : – (1) Evaluate <actuals> ;– (2) Substitute the result of (1) for the formals in
the body ;– (3) Evaluate the body of <name> ;– (4) Return the result of (3) as the answer.
let fun f x = x + 1 + x in f (2 + 3) end ;
bodyformals
actuals
![Page 31: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/31.jpg)
fun f x = x + 2 + x ;
f (2+3) ==> f (5)==> 5 + 2 + 5==> 12
fun g x y = if (x < 3) then y else x;
g 3 (4/0) ==> g 3 ==>
• Also referred to as call-by-value evaluation.
• Occasionally, arguments are evaluated unnecessarily.
![Page 32: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/32.jpg)
Outermost Evaluation Strategy
• To Evaluate <name><actuals> :• (1) Substitute actuals for the formals in the body ;• (2) Evaluate the body ;• (3) Return the result of (2) as the answer.
fun f x = x + 2 + x ;f (2+3) ==> (2+3) + 2 + (2+3)
==> 12fun g x y = if x < 3 then y else x ;g 3 (4/0) ==> if 3 < 3 then (4/0) else 3
==> 3
![Page 33: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/33.jpg)
It is possible to eliminate redundant computation in outermost evaluation strategy.
fun f x = x + 2 + x ;f (2+3) ==> x + 2 + x
==> 5 + 2 + x
==> 7 + x ==> 7 + 5 ==> 12
5
x=(2+3)
Note: Arguments are evaluated only when they are needed.
![Page 34: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/34.jpg)
Why Use Outermost Strategy?
• Closer to the meaning of mathematical functions
fun k x y = x ;val const1 = k 1 ;val const2 = k 2 ;
• Better modeling of real mathematical objectsval naturalNos = let fun inf n = n :: inf (n+1) in inf 1 end ;
![Page 35: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/35.jpg)
Hamming Number
List, in ascending order with no repetition, all positive integers with no prime factors other than 2, 3, or 5.
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,...
![Page 36: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/36.jpg)
n as a prime factor
fun scale n [] = []| scale n (x::xs) = (n*x) :: (scale n xs)
scale 2 [1,2,3,4,5] = [2,4,6,8,10]
scale 3 [1,2,3,4,5] = [3,6,9,12,15]
scale 3 (scale 2 [1,2,3,4,5]) = [6,12,18,24,30]
![Page 37: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/37.jpg)
Merging two Streams
fun merge [] [] = []| merge (x::xs) (y::ys) =
if x < y then x :: merge xs (y::ys)else if x > y then y :: merge (x::xs) ys
else x :: merge xs ys
merge [2,4,6] [3,6,9] = [2,3,4,6,9]
![Page 38: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/38.jpg)
Hamming numbers
val hamming = 1 :: merge (scale 2 hamming)
(merge (scale 3 hamming) (scale 5 hamming))
::
1
mergemerge
scale 3
scale 5
scale 2
![Page 39: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/39.jpg)
Outline
• More about Higher-order Function
• Type inference and Polymorphism
• Evaluation Strategies
• Exception Handling
![Page 40: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/40.jpg)
Exception Handling• Handle special cases or failure (the exceptions) occurred during program execution.
hd []; uncaught exception hd
• Exception can be raised and handled in the program. exception Nomatch;
exception Nomatch : exn
fun member(a,x) = if null(x) then raise Nomatch else if a = hd(x) then x else member(a,tl(x))
![Page 41: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/41.jpg)
fun member(a,x) = if null(x) then raise Nomatch else if a = hd(x) then x else member(a,tl(x))
member(3,[1,2,3,1,2,3]) ; val it = [3,1,2,3] : int listmember(4,[]) ; uncaught exception Nomatchmember(5,[1,2,3]) handle Nomatch=>[]; val it = [] : int list
![Page 42: CS 2104 – Prog. Lang. Concepts Functional Programming II](https://reader035.vdocuments.site/reader035/viewer/2022062321/56813bd6550346895da4fc7c/html5/thumbnails/42.jpg)
Conclusion
• More about Higher-order Function
– Curried vs Uncurried functions
– Full vs Partial Application
• Type inference and Polymorphism
– Basic Type inference rules
– Polymorphic functions
• Evaluation Strategies
– Innermost
– Outermost
• Exception Handling is available in ML