Title: Haskell Examples
1Haskell Examples
2Factorial
fact n if n 0 then 1 else n fact (n
- 1)
fac 0 1 fac (n1) (n1)fac n
3Quadratic Formula
quadsolve a b c delta lt 0 error
"complex roots" delta 0 -b/(2a)
delta gt 0 -b/(2a) radix/(2a),
-b/(2a) - radix/(2a)
where delta bb - 4ac
radix sqrt delta
Maingt quadsolve 1 4 (-12) 2.0,-6.0
4Permutations
perms a -gt a perms perms
(ht) take n x h drop n x
n lt- 0..length t, x lt- perms t
Maingt perms "abc" "abc","acb","bac","cab","bca","
cba"
5Pig Latin
- Pig Latin is a childs secret language
- Rearranges sounds in words depending on whether
word begins with a vowel sound
a p p l e -gt a p p l e h a y
s t r i p e -gt i p e s t r a y
6Pig Latin for single words
latinizeWord w back w front w suffix w
where front w fst (breakWord w) back
w snd (breakWord w) suffix w if
front w "" then "hay"
else "ay" breakWord w
span (notElem "aeiou") w
Maingt latinizeWord "stripe" "ipestray"
7Pig Latin for sentences I
Maingt words "Haskell is fun" "Haskell","is","fun"
Maingt unwords (words "Haskell is fun") "Haskell
is fun"
Maingt unwords (words "Haskell is fun") "Haskell
is fun"
8Pig Latin for sentences II
latinize s unwords (map latinizeWord (words
s))
Maingt latinize "Haskell is fun" "askellHay ishay
unfay"
9unwords
- words and unwords are already defined in the
Standard Prelude
unwords String -gt String unwords
"" unwords ws foldr1 (\w s -gt w ' 's)
ws
10unwords (again)
unwds Char -gt Char unwds unwds
s_at_(ht) h " " unwds t
11Fibonacci Numbers
Maingt zip 'a'..'z' 1..5 ('a',1),('b',2),('c',
3),('d',4),('e',5)
fib 11ab (a, b) lt- zip fib (tail fib)
Maingt take 10 fib 1,1,2,3,5,8,13,21,34,55
12The End