Presentation is loading. Please wait.

Presentation is loading. Please wait.

Haskell Examples 10-May-19.

Similar presentations


Presentation on theme: "Haskell Examples 10-May-19."— Presentation transcript:

1 Haskell Examples 10-May-19

2 Factorial fact n = if n == 0 then 1 else n * fact (n - 1) fac 0 = 1
fac (n+1) = (n+1)*fac n

3 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]

4 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"]

5 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

6 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"

7 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"

8 Pig Latin for sentences II
latinize s = unwords (map latinizeWord (words s)) Main> latinize "Haskell is fun" "askellHay ishay unfay"

9 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

10 unwords (again) unwds :: [[Char]] -> [Char] unwds [] = []
unwds (h:t) = h ++ " " ++ unwds t

11 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]

12 The End


Download ppt "Haskell Examples 10-May-19."

Similar presentations


Ads by Google