Programming in Haskell: Chapter 2 - First Steps
Programming in Haskell: Chapter 2 - First Steps
1
Glasgow Haskell Compiler
www.haskell.org/platform
2
Starting GHCi
$ ghci
Prelude>
> 2+3*4
14
> (2+3)*4
20
4
The Standard Prelude
5
Remove the first element from a list:
> [1,2,3,4,5] !! 2
3
Reverse a list:
f(a,b) + c d
f a b + c*d
10
Moreover, function application is assumed to have
higher priority than all other operators.
fa+b
11
Examples
Mathematics Haskell
f(x) fx
f(x,y) fxy
f(g(x)) f (g x)
f(x,g(y)) f x (g y)
f(x)g(y) fx*gy
12
Haskell Scripts
13
My First Script
double x = x + x
$ ghci test.hs
> quadruple 10
40
Note:
> :reload
Reading file "test.hs"
> factorial 10
3628800
17
Useful GHCi Commands
Command Meaning
xs ns nss
19
The Layout Rule
a = 10 a = 10 a = 10
b = 20 b = 20 b = 20
c = 30 c = 30 c = 30
20
The layout rule avoids the need for explicit syntax
to indicate the grouping of definitions.
a=b+c a=b+c
where where
b=1 means {b = 1;
c=2 c = 2}
d=a*2 d=a*2
N = a ’div’ length xs
where
a = 10
xs = [1,2,3,4,5]
22
(3) Show how the library function last that selects
the last element of a list can be defined using
the functions introduced in this lecture.
23