-
Notifications
You must be signed in to change notification settings - Fork 39
/
Adapter.hs
51 lines (40 loc) · 1.51 KB
/
Adapter.hs
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
module Adapter where
backend :: c -> d
backend = undefined
marshal :: a -> c
marshal = undefined
unmarshal :: d -> b
unmarshal = undefined
adapter :: a -> b
adapter = unmarshal . backend . marshal
-- a 24:00 hour clock representation of time
newtype WallTime = WallTime (Int, Int) deriving (Show)
-- this is our backend. It can add minutes to a WallTime representation
addMinutesToWallTime :: Int -> WallTime -> WallTime
addMinutesToWallTime x (WallTime (h, m)) =
let (hAdd, mAdd) = x `quotRem` 60
hNew = h + hAdd
mNew = m + mAdd
in if mNew >= 60
then
let (dnew, hnew') = (hNew + 1) `quotRem` 24
in WallTime (24*dnew + hnew', mNew-60)
else WallTime (hNew, mNew)
-- this is our time representation in Minutes that we want to use in the frontend
newtype Minute = Minute Int deriving (Show)
-- convert a Minute value into a WallTime representation
marshalMW :: Minute -> WallTime
marshalMW (Minute x) =
let (h,m) = x `quotRem` 60
in WallTime (h `rem` 24, m)
-- convert a WallTime value back to Minutes
unmarshalWM :: WallTime -> Minute
unmarshalWM (WallTime (h,m)) = Minute $ 60 * h + m
-- this is our frontend that add Minutes to a time of a day
-- measured in minutes
addMinutesAdapter :: Int -> Minute -> Minute
addMinutesAdapter x = unmarshalWM . addMinutesToWallTime x . marshalMW
adapterDemo = do
putStrLn "Adapter -> function composition"
print $ addMinutesAdapter 100 $ Minute 400
putStrLn ""