-
-
Save dimitris-papadimitriou-chr/16d636b3c066e9051773da6f25a14a6a to your computer and use it in GitHub Desktop.
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
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