Solve functor Task 2
This commit is contained in:
parent
1708105d9f
commit
0317fcf8b1
1 changed files with 57 additions and 6 deletions
|
@ -1,22 +1,73 @@
|
|||
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)
|
||||
|
||||
test1 = unbox (fmap id b) == unbox b
|
||||
test11 = Result actual expected (actual == expected)
|
||||
where
|
||||
actual = unbox (fmap id b)
|
||||
expected = unbox b
|
||||
|
||||
b = Boxed { unbox = 1 :: Integer }
|
||||
|
||||
-- >>> test1
|
||||
-- True
|
||||
-- >>> test11
|
||||
-- Result {actual = 1, expected = 1, result = True}
|
||||
--
|
||||
|
||||
test2 = unbox (fmap (f . g) b) == unbox (fmap f $ fmap g b)
|
||||
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)
|
||||
|
||||
-- >>> test2
|
||||
-- True
|
||||
-- >>> 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}
|
||||
--
|
||||
|
|
Loading…
Reference in a new issue