-
-
Save mjrosenb/a3a22b3a7dd562b69d85f706d233242d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data MyState c b a = MyState {run :: (c, b) -> (a, (c,b))} | |
instance Functor (MyState c b) where | |
f `fmap` MyState vf = MyState rf | |
where rf ctx = let (v, ctx') = vf ctx | |
in (f v, ctx') | |
instance Applicative (MyState c b) where | |
pure v = MyState (\ctx -> (v, ctx)) | |
MyState ff <*> MyState vf = MyState rf | |
where rf ctx = let (f, ctx') = ff ctx | |
(v, ctx'') = vf ctx' | |
in (f v, ctx'') | |
instance Monad (MyState c b) where | |
MyState vf >>= f = MyState rb | |
where rb ctx = let (val, ctx') = vf ctx | |
in run (f val) ctx' | |
-- implement MonadState, so that lens can be applied to the state directly | |
instance MonadState b (MyState c b) where | |
put newSt = MyState (\(c,b) -> ((), (c, newSt))) | |
get = MyState (\(c,b) -> (b, (c,b))) | |
put_ newSt = MyState (\(c,b) -> ((), (newSt, b))) | |
get_ = MyState (\(c,b) -> (c, (c,b))) | |
use_ op = do x <- get_ | |
return (x ^. op) | |
data Foo = Foo { | |
_test_one :: Int, | |
_test_two :: Int, | |
_test_three :: Int | |
} | |
makeLenses ''Foo | |
math1 :: MyState Foo Foo () | |
math1 = do | |
x <- use test_one | |
y <- use test_two | |
test_three .= x + y | |
math2 :: MyState Foo Foo () | |
math2 = do | |
x <- use_ test_one | |
y <- use_ test_two | |
test_three .= x + y | |
math3 use' = do | |
x <- use' test_one | |
y <- use' test_two | |
test_three .= x + y |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment