Skip to content

Instantly share code, notes, and snippets.

@themoritz
Created October 26, 2017 17:23
Show Gist options
  • Save themoritz/7ef2cffa2c8f588e09f74a1c48123db7 to your computer and use it in GitHub Desktop.
Save themoritz/7ef2cffa2c8f588e09f74a1c48123db7 to your computer and use it in GitHub Desktop.
Hamburg Haskell Meetup Oct 25 2017
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
module Transformers where
import Control.Monad
data State s a = State
{ runState :: s -> (a, s)
}
instance Functor (State s) where
fmap :: (a -> b) -> State s a -> State s b
fmap f mx = mx >>= (return . f)
instance Applicative (State s) where
pure = return
(<*>) :: State s (x -> y) -> State s x -> State s y
mf <*> mx = mf >>= (flip fmap mx)
instance Monad (State s) where
return :: a -> State s a
return x = State (\s -> (x, s))
(>>=) :: State s a -> (a -> State s b) -> State s b
mx >>= f = State $ \s ->
let (x, s') = runState mx s
in runState (f x) s'
data StateT s m a = StateT
{ runStateT :: s -> m (a, s)
}
class MonadTrans t where
lift :: Functor m => m a -> t m a
instance MonadTrans (StateT s) where
lift :: Functor m => m a -> StateT s m a
lift mx = StateT $ \s -> fmap (\x -> (x,s)) mx
instance Monad m => Functor (StateT s m) where
fmap f mx = mx >>= (return . f)
instance Monad m => Applicative (StateT s m) where
pure = return
mf <*> mx = mf >>= (flip fmap mx)
instance Monad m => Monad (StateT s m) where
return :: a -> StateT s m a
return x = StateT $ \s -> return (x, s)
(>>=) :: StateT s m x -> (x -> StateT s m b) -> StateT s m b
mx >>= f = StateT $ \s -> do
(x, s') <- runStateT mx s
runStateT (f x) s'
class Monad m => MonadState s m where
get :: m s
put :: s -> m ()
instance Monad m => MonadState s (StateT s m) where
get :: StateT s m s
get = StateT $ \s -> return (s, s)
put :: s -> StateT s m ()
put s = StateT $ \_ -> return ((), s)
modify :: MonadState s m => (s -> s) -> m ()
modify f = do
old <- get
put (f old)
inc :: StateT Int IO ()
inc = do
char <- lift getChar
modify (+ fromEnum char)
main :: IO ()
main = do
(result, newState) <- runStateT (replicateM 10 inc) 10
print newState
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment