Skip to content

Instantly share code, notes, and snippets.

@mikesorae
Created December 17, 2018 02:11
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 mikesorae/1e27213c0aca0df0ccea585979922469 to your computer and use it in GitHub Desktop.
Save mikesorae/1e27213c0aca0df0ccea585979922469 to your computer and use it in GitHub Desktop.
State Monad with Elm
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