Title: CS5205: Foundations in Programming Languages FP with Haskell
1CS5205 Foundations in Programming Languages
FP with Haskell
A pure lazy functional language that embodies
many innovative ideas in language design.
2 Haskell
- Advanced programming language reusable,
abstract, efficient, feature-rich. - Functions and Expressions
- Values, Types and Lazy evaluation
- Products, Records and Algebraic Types
- Polymorphic Types Type Classes
- Higher-Order Functions
- Infix operator and sections.
Reference --- A Gentle Introduction to Haskell
98 http//www.haskell.org/tutorial
3 Functions
- Function is a black box that converts input to
output. A basis of software component.
pure
4 Example of Functions
square Int -gt Int square x xx
5 Expression-Oriented
- Instead of imperative commands/statements, the
focus is on expression.
- Instead of command/statement
- if e1 then stmt1 else stmt2
- We use conditional expressions
- if e1 then e2 else e3
6 Expression-Oriented
fact Integer -gt Integer fact n if n0 then
1 else n fact (n-1)
7Conditional ? Case Construct
- Conditional
- if e1 then e2 else e3
case e1 of True -gt e2 False -gt e3
8 Lexical Scoping
- Local variables can be created by let construct
to give nested scope for the name space. Example
let y ab f x (xy)/y in f c f d
9 Layout Rule
- Haskell uses two dimensional syntax that relies
on declarations being lined-up columnwise
let y ab f x (xy)/y in f c f d
is being parsed as
let y ab f x (xy)/y in f c f d
- Rule Next character after keywords
where/let/of/do determines the starting columns
for declarations. Starting after this point
continues a declaration, while starting before
this point terminates a declaration.
10 Expression Evaluation
- Expression can be computed (or evaluated) so that
it is reduced to a value. This can be represented
as
e ? .. ? v
- We can abbreviate above as
e ? v
- Type preservation theorem says that
- if e t Æ e ? v , it follows that v t
11 Values and Types
- As a purely functional language, all computations
are done via evaluating expressions (syntactic
sugar) to yield values (normal forms as answers). - Each expression has a type which denotes the set
of possible outcomes. - v t can be read as value v has type t.
- Examples of typings, associating a value with its
corresponding type are
5 Integer 'a' Char 1,2,3
Integer ('b', 4) (Char, Integer) cs5
String (same as Char)
12 Built-In Types
data Char a b data Int -65532
-1 0 1 . 65532 data Integer
-2 -1 0 1 2
13 User-Defined Algebraic Types
- Can describe enumerations
data Bool False True data Color Red
Green Blue Violet
14 Recursive Types
- Some types may be recursive
data Tree a Leaf a Branch (Tree a) (Tree a)
15 Polymorphic Types
- Support types that are universally quantified in
some way over all types.
- 8 c. c denotes a family of types, for every
type c, the type of lists of c. - Covers Integer, Char, Integer-gtInteger,
etc.
16 Polymorphic Types
- This polymorphic function can be used on list of
any type..
length 1,2,3 ) 2 length a, b, c
) 3 length 1,,3 ) 3
- Note that head/tail are partial functions, while
length is a total function?
17 Principal Types
- Some types are more general than others
Char lt 8 a. a lt 8 a. a
- An expressions principal type is the least
general type that contains all instances of the
expression. - For example, the principal type of head function
is - a-gta, while b -gt a, b -gt a, a are correct
but too general but Integer -gt Integer is too
specific. - Principal type can help supports software
reusability with accurate type information.
18 Type Synonyms
- It is possible to provide new names for commonly
used types
type String Char type Person (Name,
Address) type Name String data Address None
Addr String
- Their use can improve code readability.
19 Type Classes and Overloading
- Parametric polymorphism works for all types.
However, ad-hoc polymorphism works for a class of
types and can systematically support overloading.
20 Equality Class
- Similar issue with equality. Though it looks like
() a -gt a -gt Bool
- Equality can be tested for data structures but
not functions!
- Solution is to define a type class that supports
the equality method, as follows
class Eq a where (),(/) a -gt a -gt Bool x
/ y not (xy)
default definition
() Eq a gt a -gt a -gt Bool
21 Members of Eq Type Class
- The class is open and can be extended, as follows
instance Eq Integer where x y x integerEq
y
instance Eq Float where x y x FloatEq y
22 More Members of Eq Type Class
- Similarly, we may use structural equality for
List
instance (Eq a) gt Eq (a) where
True (xxs) (yys) (xy) (xsys) _
_ False
elem (Eq a) gt a -gt a -gt Bool x elem
False x elem (yys) (xy) (x elem ys)
- Exercise define Set as an instance of the Eq
class.
23 Numeric Class
- There is a hierarchy of numeric classes. Most
basic is
class Num a where (),(-),() a -gt a -gt a
negate,abs,signum a -gt a fromInteger
Integer -gt a x y x (negate y)
negate x 0 x instance Num Int where
instance Num Integer where instance Num
Float where instance Num Double where
24 Functions and its Type
- Method to increment its input
inc x x1
- Or through lambda expression (anonymous functions)
(\ x -gt x1)
- They can also be given suitable function typing
inc Num a gt a -gt a (\x -gt x1) Num a gt
a -gt a
- Types can be user-supplied or inferred.
25 Functions and its Type
(\x -gt x1) 3.2 ?
(\x -gt x1) 3 ?
26 Function Abstraction
- Function abstraction is the ability to convert
any expression into a function that is evaluated
at a later time.
ltExprgt
p \ () -gt ?Expr?
time
p ()
time
Normal Execution
Delayed Execution
27 Higher-Order Functions
- Higher-order programming treats functions as
first-class, allowing them to be passed as
parameters, returned as results or stored into
data structures.
- This concept supports generic coding, and allows
programming to be carried out at a more abstract
level.
- Genericity can be applied to a function by
letting specific operation/value in the function
body to become parameters.
28 Functions
- Functions can be written in two main ways
add Integer -gt Integer -gt Integer add x y
xy
add2 (Integer,Integer) -gt Integer add2(x,y)
xy
- The first version allows a function to be
returned as result after applying a single
argument.
inc Integer -gt Integer inc add 1
- The second version needs all arguments. Same
effect requires a lambda abstraction
inc \ x -gt add2(x,1)
29 Functions
- Functions can also be passed as parameters.
Example
map (a-gtb) -gt a -gt b map f
map f (xxs) (f x) (map f xs)
30 Genericity
- Replace specific entities (0 and ) by
parameters.
sumList ls case ls of -gt 0 xxs
-gt x(sumList xs)
31 Polymorphic, Higher-Order Types
sumList Int -gt Int sumList Num a gt a
-gt a
32 Instantiating Generic Functions
sumL2 Num a gt a -gt a sumL2 ls foldr () 0
ls
sumL2 1, 2, 3 ) sumL2 1.1, 3, 2.3 )
33 Instantiating Generic Functions
prodL Num a gt a -gt a prodL ls foldr () 1
ls
prodL 1, 2, 5 ) prodL 1.1, 3, 2.3 )
34 Instantiating Generic Functions
- Can you express map in terms of foldr?
map (a -gt b) -gt a -gt b map f map
f (xxs) (f x) (map f xs)
map f xs foldr xs
35 Instantiating Generic Functions
- Filtering a list of elements with a predicate.
filter (a -gt Bool) -gt a -gt a filter f
filter f (xxs) if (f x) then x
(filter f xs) else x filter f xs
36 Pipe/Compose
compose (b -gt c) -gt (a -gt b) -gt a -gt
c compose f g \ x -gt f (g x) g f compose
f g
37 Iterator Construct
for Int -gt Int -gt (Int -gt a -gt a) -gt a -gt
a for i j f a if igtj then a else f (i1) j
(f i a)
38 Right Folding
- foldr f u x1,x2,..,xn
- f x1 (foldr f u x2 ..xn)
- f x1 (f x2 (fold f u x3..xn))
- f x1 (f x2 ( (fold f u xn) ))
- f x1 (f x2 ( (f xn u) )))
39 Left Folding Tail Recursion
- Accumulate result in a parameter
foldl f u ls case ls of -gt u
xxs -gt foldl f (f u x) xs
based on accumulation
- What is the type of foldl?
- Can we compute factorial using it?
40 Left Folding
- foldl f u x1,x2,..,xn
- foldl f (f u x1) x2 ..xn
- foldl f (f (f u x1) x2) x3..xn))
- foldl f (f (f (f u x1) x2) xn)
- f ( (f (f u x1) x2) ) xn
41 Instance of Left Folding
- Summing a list by accumulation.
sumT acc ls case ls of -gt 0 xxs
-gt sumT (xacc) xs
42 Infix Operator
- Infix operators are distinguished entirely by
symbols
() a-gt a -gt a ys ys (xxs)
ys x (xs ys)
- Another example is function composition.
(.) (b-gtc) -gt (a-gtb) -gt (a-gtc) f . g \ x
-gt f (g x)
- Infix operator can be coerced to prefix by
bracketing, - e.g. map () 1,2,3
- Alphanumeric named function can be made infix
too, - e.g. a add b x elem xs
43 Sections
- Infix operators can also be partially applied
(x) \y -gt xy (y) \x -gt xy () \x y
-gt xy
inc ( 1) add ()
- These are syntactic sugar for programming
conveniences.