Last active
April 18, 2017 06:50
-
-
Save jpablo/5d423acd2811a863b3597777d64b8263 to your computer and use it in GitHub Desktop.
State instances: Functor, Applicative, Monad
This file contains hidden or 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
{-# 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