Last active
December 11, 2015 15:29
-
-
Save margnus1/4621499 to your computer and use it in GitHub Desktop.
A Haskell-like state monad in Standard ML
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
| 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