03 Haskell
03 Haskell
Clem Baker-Finch
fac 0 = 1
fac n = n * fac ( n - 1)
Rewriting a pure program in a different order does not change its final value.
fac 3 fac 3
=) 3 * fac 2 =) 3 * fac 2
=) 3 * 2 * fac 1 =) 6 * fac 1
=) 3 * 2 * 1 * fac 0 =) 6 * fac 0
=) 3 * 2 * 1 * 1 =) 6 * 1
=) 6 =) 6
Purity makes a program easier to understand, for both people and compilers.
fac n
= do result = 1
while n > 1
result := result * n
n := n - 1
return result
We will learn how to reason about both pure and impure programs.
The function fac accepts a value, and produces a value — but not all work.
fac " toast " = " toast " * fac ( " toast " - 1)
= ???
We can partially apply the add function by providing just one argument.
addTwo 3
=) (add 2) 3
=) add 2 3
=) 2 + 3
=) 5
The Prelude defines some useful functions for extracting the components.
fst (x , y ) = x
snd (x , y ) = y
[1 , 2 , 3] (1 : [2 , 3]) (1 : 2 : 3 : [])
We use pattern matching and recursion to write functions that deal with lists.
length [] = 0
length ( x : xs ) = 1 + length xs
The length function does not inspect the elements of a list. It is only
concerned about the list’s structure.
length [2 , 3 , 5] = 3
length [ " red " , " green " , " blue " ] = 3
fac takes an argument of type a, and produces a result of the same type, as
long as a is a number type, ie Int, Integer, Float, Double
When an equation has guards they will be tried from first to last.
We can define our own types by specifying how values of that type are
constructed.
data Shape
= Circle Float
| Rectangle Float Float
deriving ( Eq , Show )
area (Rectangle 2 3)
=) 2 * 3
=) 6
We can define our own types which behave the same way
data Tuple2 a b = T2 a b
data List a = Nil | Cons a ( List a)
data Tree a
= Null
| Node a ( Tree a ) ( Tree a )
Invariant
The keys in the left hand subtree of that node are always less than k.
The keys in the right hand subtree are always more than k.
13 42
5 16 31 68
6
( Node 23 ( Node 13 ( Node 5 Null
( Node 6 Null Null ))
( Node 16 Null Null ))
( Node 42 ( Node 31 Null Null )
( Node 68 Null Null )))