Haskell Examples 01 Dec20 Factorial fact n if

  • Slides: 12
Download presentation
Haskell Examples 01 -Dec-20

Haskell Examples 01 -Dec-20

Factorial fact n = if n == 0 then 1 else n * fact

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"

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)

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

Pig Latin n n Pig Latin is a child’s “secret language” Rearranges sounds in

Pig Latin n n 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 latinize. Word w = back w ++ front w

Pig Latin for single words latinize. Word w = back w ++ front w ++ suffix w where front w = fst (break. Word w) back w = snd (break. Word w) suffix w = if front w == "" then "hay" else "ay" break. Word w = span (`not. Elem` "aeiou") w Main> latinize. Word "stripe" "ipestray"

Pig Latin for sentences I Main> words "Haskell is fun" ["Haskell", "is", "fun"] Main>

Pig Latin for sentences I Main> 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 latinize. Word (words s))

Pig Latin for sentences II latinize s = unwords (map latinize. Word (words s)) Main> latinize "Haskell is fun" "askell. Hay ishay unfay"

unwords n words and unwords are already defined in the Standard Prelude unwords :

unwords n words and unwords are already defined in the Standard Prelude unwords : : [String] -> String unwords [] = "" unwords ws = foldr 1 (w s -> w ++ ' ': s) ws

unwords (again) unwds : : [[Char]] -> [Char] unwds [] = [] unwds (h:

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

Fibonacci Numbers Main> zip ['a'. . 'z'] [1. . 5] [('a', 1), ('b', 2),

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

The End