Skip to content

Instantly share code, notes, and snippets.

@itsfarseen
Forked from merijn/MyState.hs
Last active January 6, 2020 09:34
Show Gist options
  • Save itsfarseen/55b8c406770a52a32da5292528e8adfe to your computer and use it in GitHub Desktop.
Save itsfarseen/55b8c406770a52a32da5292528e8adfe to your computer and use it in GitHub Desktop.
MyState homework solution
data MyState s a = MyState (s -> (a,s))
get :: MyState s s
get = MyState (\s -> (s, s))
put :: s -> MyState s ()
put s = MyState (\_ -> ((), s))
modify :: (s -> s) -> MyState s ()
modify f = MyState (\s -> ((), f s))
instance Functor (MyState s) where
-- Why did they put (MyState s) a instead of MyState s a?
-- fmap :: (a -> b) -> (MyState s) a -> (MyState s) b
fmap f (MyState g) = MyState $ \s ->
let (x, s') = g s
y = f x
in (y, s')
instance Applicative (MyState s) where
pure x = MyState $ \s -> (x, s)
-- (<*>) :: (MyState s) (a->b) -> (MyState s) a -> (MyState s) b
(<*>) (MyState f) (MyState g) = MyState $ \s ->
let (f', s' ) = f s
(a , s'') = g s'
in (f' a, s'')
instance Monad (MyState s) where
return = pure
-- (>>=) :: (MyState s) a -> (a-> (MyState s) b) -> (MyState s) b
(>>=) (MyState f) f' = MyState $ \s ->
let (a, s') = f s
MyState g' = f' a
(b, s'') = g' s'
in (b, s'')
main = print "Hello World!"
data MyStateT s m a = MyStateT (s -> m (a, s))
get :: Monad m => MyStateT s m s
get = undefined
put :: Monad m => s -> MyStateT s m ()
put = undefined
modify :: Monad m => (s -> s) -> MyStateT s m ()
modify = undefined
instance Monad m => Functor (MyStateT s m) where
-- fmap :: (a -> b) -> (MyStateT s m) a -> (MyStateT s m) b
fmap = undefined
instance Monad m => Applicative (MyStateT s m) where
-- pure :: a -> (MyStateT s m) a
pure = undefined
-- (<*>) :: (MyStateT s m) (a -> b) -> (MyStateT s m) a -> (MyStateT s m) b
(<*>) = undefined
instance Monad m => Monad (MyStateT s m) where
-- return :: a -> (MyStateT s m) a
return = pure
-- (>>=) :: (MyStateT s m) a -> (a -> (MyStateT s m) b) -> (MyStateT s m) b
(>>=) = undefined
instance MonadTrans (MyStateT s) where
-- lift :: Monad m => m a -> MyStateT s m a
lift = undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment