Professional Documents
Culture Documents
Chapter 05
Chapter 05
PROGRAMMING IN HASKELL
total = 0;
for (i = 1; i 10; ++i)
total = total+i;
sum [1..10]
?
Karadeniz Teknik Üniversitesi Chapter Five Programming Languages 9
The Hugs System
• Hugs is an implementation of Haskell 2006,
and is the most widely used Haskell system;
% hugs
Haskell 98 mode: Restart with command line option -98 to enable extensions
For example:
> 2+3*4
14
> (2+3)*4
20
> [1,2,3,4,5] !! 2
3
Reverse a list:
f(a,b) + c d
f a b + c*d
f a + b
f(x) f x
f(x,y) f x y
f(g(x)) f (g x)
f(x,g(y)) f x (g y)
f(x)g(y) f x * g y
double x = x + x
% hugs test.hs
> quadruple 10
40
Note:
> :reload
Reading file "test.hs"
> factorial 10
3628800
xs ns nss
a = 10 a = 10 a = 10
b = 20 b = 20 b = 20
c = 30 c = 30 c = 30
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]
Bool
False True
> 1 + False
Error
e :: t
[False,True,False] :: [Bool]
[’a’,’b’,’c’,’d’] :: [Char]
In general:
[False,True] :: [Bool]
[False,True,False] :: [Bool]
[[’a’],[’b’,’c’]] :: [[Char]]
(False,True) :: (Bool,Bool)
(False,’a’,True) :: (Bool,Char,Bool)
In general:
(False,True) :: (Bool,Bool)
(False,True,False) :: (Bool,Bool,Bool)
(’a’,(False,’b’)) :: (Char,(Bool,Char))
(True,[’a’,’b’]) :: (Bool,[Char])
In general:
For example:
mult x y z
Means ((mult x) y) z.
fst :: (a,b) a
head :: [a] a
id :: a a
For example:
(+) :: Num a a a a
(==) :: Eq a a a Bool
(<) :: Ord a a a Bool
[’a’,’b’,’c’]
(’a’,’b’,’c’)
[(False,’0’),(True,’1’)]
([False,True],[’0’,’1’])
[tail,init,reverse]
pair x y = (x,y)
double x = x*2
palindrome xs = reverse xs == xs
twice f x = f (f x)