Skip to content

Instantly share code, notes, and snippets.

@jonifreeman
Created April 6, 2012 16:58
Show Gist options
  • Save jonifreeman/2321316 to your computer and use it in GitHub Desktop.
Save jonifreeman/2321316 to your computer and use it in GitHub Desktop.
State monad in Roy
data State_t a s = State a s
let unit = {}
let stateMonad = {
return: \x -> \s -> State x s
bind: \sm f -> \s0 -> match (sm s0)
case (State x s) = (f x) s
}
let runState sm s = sm s
let getState = \s -> State s s
let putState x = \s -> State unit x
let plusFiveTimesFour = (do stateMonad
x <- getState
_ <- putState (x + 5)
y <- getState
return (y * 4)
)
runState plusFiveTimesFour 10
//////////////////////////////////////////////////////////////////
Outputs:
{"_0":60,"_1":15}
//////////////////////////////////////////////////////////////////
Generated Javascript:
var State = function(a_0, s_1) {
if(!(this instanceof State)) {
return new State(a_0, s_1);
}
this._0 = a_0;
this._1 = s_1;
};
var unit = {
};
var stateMonad = {
"return": function(x) {
return function(s) {
return State(x, s);
};
},
"bind": function(sm, f) {
return function(s0) {
return (function() {
if((sm(s0)) instanceof State) {
var x = (sm(s0))._0;
var s = (sm(s0))._1;
return f(x)(s);
}
})();
};
}
};
var runState = function(sm, s) {
return sm(s);
};
var getState = function(s) {
return State(s, s);
};
var putState = function(x) {
return function(s) {
return State(unit, x);
};
};
var plusFiveTimesFour = ((function(){
var __monad__ = stateMonad;
return __monad__.bind(getState, function(x) {
return __monad__.bind(putState((x + 5)), function(_) {
return __monad__.bind(getState, function(y) {
return __monad__.return((y * 4));
});
});
});
})());
runState(plusFiveTimesFour, 10);
@raimohanska
Copy link

Nice excercise. The dummy binding on line 20 seems unnecessary though:

_ <- putState (x + 5)

Or does Roy require this?

@jonifreeman
Copy link
Author

Current Roy (I tried with latest from master) requires that dummy binding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment