-
Notifications
You must be signed in to change notification settings - Fork 0
/
example2.hs
55 lines (41 loc) · 1.79 KB
/
example2.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
52
53
54
55
{-# LANGUAGE TypeFamilies, FlexibleContexts, GADTs #-}
-- This example demonstrates how to create your own
-- instances of the Wait typeclass, to implement custom
-- eventual contexts.
module Main where
import Eventual
data MyContext = MyContext (Maybe String) (Maybe Int) deriving (Show)
data MyContextEventualGetter v where
EventualFirst :: MyContextEventualGetter String
EventualSecond :: MyContextEventualGetter Int
data MyContextEventualUpdate
= UpdateFirst String
| UpdateSecond Int
data MyContextTrigger
= TriggerFirst
| TriggerSecond deriving (Ord, Eq)
instance Wait MyContext where
type EventualGetter MyContext = MyContextEventualGetter
type EventualUpdate MyContext = MyContextEventualUpdate
type TriggerID MyContext = MyContextTrigger
tryGetNow EventualFirst (MyContext (Just first) _) = Right first
tryGetNow EventualFirst (MyContext Nothing _) = Left TriggerFirst
tryGetNow EventualSecond (MyContext _ (Just second)) = Right second
tryGetNow EventualSecond (MyContext _ Nothing) = Left TriggerSecond
updateNow (UpdateFirst first) (MyContext _ second) = (MyContext (Just first) second, TriggerFirst)
updateNow (UpdateSecond second) (MyContext first _) = (MyContext first (Just second), TriggerSecond)
op1 :: Eventual MyContext ()
op1 = do
meaningOfLife <- waitGet $ EventualSecond
let message = "The meaning of life is: " ++ (show meaningOfLife)
update $ UpdateFirst message
op2 :: Eventual MyContext ()
op2 = update $ UpdateSecond 42
main = do
let state0 = eventualState $ MyContext Nothing Nothing
let state1 = runEventual op1 state0
putStrLn "After op1:"
print $ storageNow state1 -- prints: MyContext Nothing Nothing
let state2 = runEventual op2 state1
putStrLn "After op2:"
print $ storageNow state2 -- prints: MyContext (Just "The meaning of life is: 42") (Just 42)