Skip to content

Instantly share code, notes, and snippets.

@dimitris-papadimitriou-chr
Last active October 27, 2020 18:28
Show Gist options
  • Save dimitris-papadimitriou-chr/16d636b3c066e9051773da6f25a14a6a to your computer and use it in GitHub Desktop.
Save dimitris-papadimitriou-chr/16d636b3c066e9051773da6f25a14a6a to your computer and use it in GitHub Desktop.
import { log } from "./log.js";
import { State } from "./state.js";
import { match } from "./utils.js";
// javascript implementation of the example - 1 of the State monad in hasklell
//https://wiki.haskell.org/State_Monad#Complete_and_Concrete_Example_1
var playGame = charSequence =>
match(charSequence)({
// pattern matching on the array
empty: () => State(s => s), //terminates
cons: (x, xs) =>
State(({ on, counter }) => {
if (x == "a" && on)
return { state: { on: on, counter: counter + 1 } };
else if (x == "b" && on)
return { state: { on: on, counter: counter - 1 } };
else if (x == "c")
return { state: { on: !on, counter: counter } };
}).bind(_ => playGame(xs))
});
var startGame = charSequence =>
playGame(charSequence).run({ on: true, counter: 0 });
var display = resultState => log(JSON.stringify(resultState));
display(startGame(Array.from("aa")));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment