Skip to content

Instantly share code, notes, and snippets.

@margnus1
Last active December 11, 2015 15:29
Show Gist options
  • Select an option

  • Save margnus1/4621499 to your computer and use it in GitHub Desktop.

Select an option

Save margnus1/4621499 to your computer and use it in GitHub Desktop.
A Haskell-like state monad in Standard ML
datatype ('a, 'b) state = State of ('a -> 'b * 'a)
infix >>= >>
fun runState (State f) s =
f s
fun op>>= (act1, fact2) =
State (fn s =>
let
val (iv, is) = runState act1 s
val act2 = fact2 iv
in
runState act2 is
end)
fun (State f) >> (State g) =
State (fn s => g (#2 (f s)))
fun return v = State (fn s => (v, s))
val get = State (fn s => (s, s))
fun put s = State (fn _ => ((), s))
fun modify f = State (fn s => ((), f s))
fun gets f = State (fn s => (f s, s))
fun evalState s = #1 o runState s
fun execState s = #2 o runState s;
(* Represents the function
time state;
time deltaTime() {
time old = state;
state = Time.now();
time new = state;
return new - old;
} *)
val deltaTime = (get >>= (fn old =>
put (Time.now ()) >>
get >>= (fn new =>
return (Time.- (new, old)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment