summaryrefslogtreecommitdiff
path: root/Haskell-book/08/src/Exercises.purs
diff options
context:
space:
mode:
Diffstat (limited to 'Haskell-book/08/src/Exercises.purs')
-rw-r--r--Haskell-book/08/src/Exercises.purs72
1 files changed, 72 insertions, 0 deletions
diff --git a/Haskell-book/08/src/Exercises.purs b/Haskell-book/08/src/Exercises.purs
new file mode 100644
index 0000000..12460a8
--- /dev/null
+++ b/Haskell-book/08/src/Exercises.purs
@@ -0,0 +1,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))