zhaw-fup/Exercises/exercise-5/Solution.hs

74 lines
1.7 KiB
Haskell

import Data.Char
data Result t =
Result {
actual :: t,
expected :: t,
result :: Bool
} deriving (Show, Eq, Ord)
--------------------
-- Exercise 1
--------------------
newtype Boxed a = Boxed {unbox :: a}
instance Functor Boxed where
fmap f (Boxed a) = Boxed (f a)
test11 = Result actual expected (actual == expected)
where
actual = unbox (fmap id b)
expected = unbox b
b = Boxed { unbox = 1 :: Integer }
-- >>> test11
-- Result {actual = 1, expected = 1, result = True}
--
test12 = Result actual expected (actual == expected)
where
actual = unbox (fmap (f . g) b)
expected = unbox (fmap f $ fmap g b)
b = Boxed { unbox = 1 :: Integer }
f = (+9)
g = (*11)
-- >>> test12
-- Result {actual = 20, expected = 20, result = True}
--
--------------------
-- Exercise 2
--------------------
newtype FromInt b = FromInt {fun :: Int -> b}
instance Functor FromInt where
fmap f (FromInt b) = FromInt (\ x -> f (b x))
test21 = Result actual expected (actual == expected)
where
actual = ((fun (fmap id converter)) x)
expected = (fun (converter) x)
converter = FromInt {fun = \ val -> val * (-1)}
x = 2
-- >>> test21
-- Result {actual = -2, expected = -2, result = True}
--
test22 = Result actual expected (actual == expected)
where
actual = (fun (fmap g $ fmap f converter)) x
expected = (fun ((g . f) <$> converter)) x
converter = FromInt {fun = \ val -> chr ((ord 'A') + val)}
f = \ char -> char:"B"
g = \ str -> str ++ "C"
x = 7
-- >>> test22
-- Result {actual = "HBC", expected = "HBC", result = True}
--