Created
December 17, 2018 02:11
-
-
Save mikesorae/1e27213c0aca0df0ccea585979922469 to your computer and use it in GitHub Desktop.
State Monad with Elm
This file contains 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
module ElmState exposing (..) | |
type State s a | |
= State (s -> ( a, s )) | |
push : a -> State (List a) () | |
push a = | |
State (\xs -> ( (), a :: xs )) | |
pop : State (List number) number | |
pop = | |
State <| | |
\list -> | |
case list of | |
x :: xs -> | |
( x, xs ) | |
[] -> | |
(0, [] ) -- なんとかしたい | |
join : State s (State s a) -> State s a | |
join (State outer) = | |
State <| | |
\s -> | |
let | |
( State inner, newState ) = | |
outer s | |
in | |
inner newState | |
mapValue : (a -> b) -> (s -> (a, s)) -> (s -> (b, s)) | |
mapValue f stateFn = | |
\s -> | |
let | |
( a, newState ) = | |
stateFn s | |
in | |
( f a, newState ) | |
fmap : (a -> b) -> State s a -> State s b | |
fmap f (State h) = | |
State <| mapValue f h | |
bind : State s a -> (a -> State s b) -> State s b | |
bind m f = | |
join <| fmap f m | |
andThen : (a -> State s b) -> State s a -> State s b | |
andThen f m = bind m f | |
runState : s -> State s a -> (a, s) | |
runState st (State f) = f st |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment