Skip to content

Instantly share code, notes, and snippets.

@mdunsmuir
Created December 20, 2014 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdunsmuir/2ef5439e6bbaab171af7 to your computer and use it in GitHub Desktop.
Save mdunsmuir/2ef5439e6bbaab171af7 to your computer and use it in GitHub Desktop.
{-# LANGUAGE MultiParamTypeClasses,
FunctionalDependencies,
FlexibleInstances #-}
module StateT (
--StateT, runStateT,
State, runState,
MonadState,
module Control.Applicative,
module Control.Monad,
module Control.Monad.Trans
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Trans
{-
newtype StateT m s a = StateT { runStateT :: s -> m (s, a) }
instance Monad m => Monad (StateT m s) where
return x = StateT $ \s -> return (s, x)
x >>= f = StateT $ \s' -> do (s, a) <- runStateT x s'
-}
newtype State s a = State { runState :: s -> (s, a) }
instance Functor (State s) where
fmap f m = State $ \s -> let (s', a) = runState m s
in (s', f a)
instance Applicative (State s) where
pure x = State $ \s -> (s, x)
ff <*> fx = State $ \s -> let (s', f) = runState ff s
(s'', x) = runState fx s'
in (s'', f x)
instance Monad (State s) where
return x = State $ \s -> (s, x)
f >>= g = State $ \s -> let (s', a) = runState f s
in runState (g a) s'
class Monad m => MonadState s m | m -> s where
get :: m s
put :: s -> m ()
instance MonadState s (State s) where
get = State $ \s -> (s, s)
put x = State $ \_ -> (x, ())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment