summaryrefslogtreecommitdiff
path: root/Haskell-book/08/src/Exercises.purs
blob: 12460a8d8689110be4cd6c7a954d96e6693cd98a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
module Exercises where
    
import Data.Tuple (Tuple(..), fst, snd)
import Prelude

--
-- Reviewing currying
--
cattyConny :: String -> String -> String
cattyConny x y = x <> " mrow " <> y

flippy :: String -> String -> String
flippy = flip cattyConny

appedCatty :: String -> String
appedCatty = cattyConny "woops"

frappe :: String -> String
frappe = flippy "haha"

--
-- Recursion
--
-- Exercise 2
sumNumbers :: Int -> Int
sumNumbers x = sumNumbers' x 0
    where sumNumbers' 0 acc = 0
          sumNumbers' n acc = n + (sumNumbers' (n - 1) acc)

-- Exercise 2
multiply :: Int -> Int -> Int
multiply _ 0 = 0
multiply x 1 = x
multiply x y = x + multiply x (y - 1)

--
-- Fixing dividedBy
--
data DividedResult =
      Result Int
    | DividedByZero

instance showDividedResult :: Show DividedResult where
    show :: DividedResult -> String
    show (Result n)    = show n
    show DividedByZero = show "Divided by zero"

go :: Int -> Int -> Int -> Tuple Int Int
go n d count
    | n < d     = Tuple count n
    | otherwise = go (n - d) d (count + 1)

abs :: Int -> Int
abs x
    | x < 0     = -x
    | otherwise = x

dividedBy :: Int -> Int -> Tuple DividedResult DividedResult
dividedBy num denom
    | denom == 0        = Tuple DividedByZero DividedByZero
    | (num * denom) < 0 = let tuple = go (abs num) (abs denom) 0 in
                                Tuple (Result (-(fst tuple))) (Result (snd tuple))
    | otherwise         = let tuple = go (abs num) (abs denom) 0 in
                                Tuple (Result (fst tuple)) (Result (snd tuple))

--
-- McCarthy 91 function
--
mc91 :: Int -> Int
mc91 n
    | n > 100   = n - 10
    | otherwise = mc91 (mc91 (n + 11))