Skip to content

Instantly share code, notes, and snippets.

@jpablo
Last active April 18, 2017 06:50
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 jpablo/5d423acd2811a863b3597777d64b8263 to your computer and use it in GitHub Desktop.
Save jpablo/5d423acd2811a863b3597777d64b8263 to your computer and use it in GitHub Desktop.
State instances: Functor, Applicative, Monad
{-# LANGUAGE InstanceSigs #-}
module State where
import Control.Monad
data Estado s a = Estado { corre :: s -> (a, s) }
instance Functor (Estado s) where
-- fmap :: (a -> b) -> Estado s a -> Estado s b
fmap f (Estado g) = Estado $ \s -> case g s of (a, s') -> (f a, s')
instance Applicative (Estado s) where
pure :: a -> Estado s a
pure a = Estado $ \s -> (a, s)
(<*>) :: Estado s (a -> b) -> Estado s a -> Estado s b
(Estado f) <*> (Estado g) = Estado corre'
where
corre' s = (f' a, s')
where
(f', _) = f s
(a, s') = g s
instance Monad (Estado s) where
return = pure
(>>=) :: Estado s a -> (a -> Estado s b) -> Estado s b
-- g :: a -> { s -> (b, s) }
(Estado f) >>= g = Estado $ \s -> case f s of (a, s') -> (corre $ g a) s'
-- (Estado f) >>= g = Estado corre'
-- where
-- corre' s = (corre $ g a) s'
-- where
-- (a, s') = f s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment