Haskell Examples 10-May-19
Factorial fact n = if n == 0 then 1 else n * fact (n - 1) fac 0 = 1 fac (n+1) = (n+1)*fac n
Quadratic Formula quadsolve a b c | delta < 0 = error "complex roots" | delta == 0 = [-b/(2*a)] | delta > 0 = [-b/(2*a) + radix/(2*a), -b/(2*a) - radix/(2*a)] where delta = b*b - 4*a*c radix = sqrt delta Main> quadsolve 1 4 (-12) [2.0,-6.0]
Permutations perms :: [a] -> [[a]] perms [] = [[]] perms (h:t) = [take n x ++ [h] ++ drop n x | n <- [0..length t], x <- perms t] Main> perms "abc" ["abc","acb","bac","cab","bca","cba"]
a p p l e -> a p p l e h a y s t r i p e -> i p e s t r a y Pig Latin Pig Latin is a child’s “secret language” Rearranges sounds in words depending on whether word begins with a vowel sound a p p l e -> a p p l e h a y s t r i p e -> i p e s t r a y
Pig 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 Main> latinizeWord "stripe" "ipestray"
Pig Latin for sentences I Main> words "Haskell is fun" ["Haskell","is","fun"] Main> unwords (words "Haskell is fun") "Haskell is fun" Main> unwords (words "Haskell is fun") "Haskell is fun"
Pig Latin for sentences II latinize s = unwords (map latinizeWord (words s)) Main> latinize "Haskell is fun" "askellHay ishay unfay"
unwords unwords :: [String] -> String unwords [] = "" words and unwords are already defined in the Standard Prelude unwords :: [String] -> String unwords [] = "" unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
unwords (again) unwds :: [[Char]] -> [Char] unwds [] = [] unwds (h:t) = h ++ " " ++ unwds t
Fibonacci Numbers Main> zip ['a'..'z'] [1..5] [('a',1),('b',2),('c',3),('d',4),('e',5)] fib = 1:1:[a+b | (a, b) <- zip fib (tail fib)] Main> take 10 fib [1,1,2,3,5,8,13,21,34,55]
The End