Created
March 25, 2015 10:19
-
-
Save herberteuler/b24a1097c1e31170f4e6 to your computer and use it in GitHub Desktop.
Implementing MyStateT
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 MyStateT s m a = MyStateT (s -> m (a, s)) | |
runStateT :: MyStateT s m a -> s -> m (a, s) | |
runStateT = \ (MyStateT f) s -> f s | |
get :: Monad m => MyStateT s m s | |
get = MyStateT $ \ s -> return (s, s) | |
put :: Monad m => s -> MyStateT s m () | |
put = \ s -> MyStateT $ \ s' -> return ((), s) | |
modify :: Monad m => (s -> s) -> MyStateT s m () | |
modify = \ f -> MyStateT $ \ s -> return ((), f s) | |
instance Functor m => Functor (MyStateT s m) where | |
-- fmap :: (a -> b) -> (MyStateT s m) a -> (MyStateT s m) b | |
fmap = \ f g -> MyStateT $ \ s -> let x = runStateT g s | |
f' = \ (a, s) -> (f a, s) | |
in fmap f' x | |
instance (Functor m, Monad m) => Applicative (MyStateT s m) where | |
-- pure :: a -> (MyStateT s m) a | |
pure = return | |
-- (<*>) :: (MyStateT s m) (a -> b) -> (MyStateT s m) a -> (MyStateT s m) b | |
(<*>) = \ f g -> MyStateT $ \ s -> do (f', s') <- runStateT f s | |
(a', s'') <- runStateT g s' | |
return (f' a', s'') | |
instance Monad m => Monad (MyStateT s m) where | |
-- return :: a -> (MyStateT s m) a | |
return = \ a -> MyStateT $ \ s -> return (a, s) | |
-- (>>=) :: (MyStateT s m) a -> (a -> (MyStateT s m) b) -> (MyStateT s m) b | |
(>>=) = \ m f -> MyStateT $ \ s -> do (a, s') <- runStateT m s | |
let k = f a | |
runStateT k s' | |
type MyState s = MyStateT s Identity | |
runState :: MyState s a -> s -> (a, s) | |
runState = \ m s -> runIdentity (runStateT m s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment