Create a Covariant
implementation
This commit is contained in:
parent
0317fcf8b1
commit
6d53c63bdf
1 changed files with 51 additions and 0 deletions
|
@ -1,4 +1,7 @@
|
||||||
|
import Data.Bits
|
||||||
import Data.Char
|
import Data.Char
|
||||||
|
import Data.Functor.Contravariant
|
||||||
|
|
||||||
data Result t =
|
data Result t =
|
||||||
Result {
|
Result {
|
||||||
actual :: t,
|
actual :: t,
|
||||||
|
@ -71,3 +74,51 @@ test22 = Result actual expected (actual == expected)
|
||||||
-- >>> test22
|
-- >>> test22
|
||||||
-- Result {actual = "HBC", expected = "HBC", result = True}
|
-- Result {actual = "HBC", expected = "HBC", result = True}
|
||||||
--
|
--
|
||||||
|
|
||||||
|
--------------------
|
||||||
|
-- Exercise 3
|
||||||
|
--------------------
|
||||||
|
newtype ToInt b = ToInt {conv :: b -> Int}
|
||||||
|
|
||||||
|
instance Contravariant ToInt where
|
||||||
|
contramap f (ToInt g) = ToInt (\ value -> g (f value))
|
||||||
|
|
||||||
|
strHash :: String -> Int
|
||||||
|
strHash value = realHash 0 value
|
||||||
|
where
|
||||||
|
realHash acc "" = acc
|
||||||
|
realHash acc (char:str) = realHash (acc + ((ord char) .&. 0b11010110)) str
|
||||||
|
|
||||||
|
test3 = [
|
||||||
|
(Result strExpected strActual (strExpected == strActual)),
|
||||||
|
(Result expected actual (expected == actual))
|
||||||
|
]
|
||||||
|
where
|
||||||
|
-- Create object `toInt` for converting strings to an Int hash (using the "strHash" function)
|
||||||
|
toInt = ToInt strHash
|
||||||
|
|
||||||
|
-- Converting a string to an Int hash using `toInt` should yield
|
||||||
|
-- the same result like using `strHash` directly
|
||||||
|
strActual = conv toInt myStr
|
||||||
|
strExpected = strHash myStr
|
||||||
|
|
||||||
|
-- Create a function for converting a `Char` to a `String`
|
||||||
|
charToStr = \x -> [x]
|
||||||
|
|
||||||
|
-- Wrap `toInt` in a (Char -> String) converter using `contramap`
|
||||||
|
-- effectively using `toInt` as a `Char -> Int` function
|
||||||
|
actual = conv (contramap charToStr toInt) myChar
|
||||||
|
-- should yield the same result like using `charToStr` and the original `toInt` directly
|
||||||
|
expected = conv toInt (charToStr myChar)
|
||||||
|
|
||||||
|
-- Value for testing the `toInt` implementation
|
||||||
|
myStr = "Hello World"
|
||||||
|
-- Value for testing the `toInt` implementation
|
||||||
|
-- wrapped in the `charToStr` function
|
||||||
|
myChar = 'V'
|
||||||
|
|
||||||
|
-- Showing the result of the `String` and the `Char` test
|
||||||
|
-- >>> mapM_ putStrLn (map show test3)
|
||||||
|
-- Result {actual = 712, expected = 712, result = True}
|
||||||
|
-- Result {actual = 86, expected = 86, result = True}
|
||||||
|
--
|
||||||
|
|
Loading…
Reference in a new issue