Created
January 13, 2020 08:35
-
-
Save thoferon/12f7267f354d95f737e27e81533ba248 to your computer and use it in GitHub Desktop.
This file contains 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 readline from "readline-sync" | |
function read () { | |
return { | |
action: "read", | |
next: pure, | |
} | |
} | |
function print (string) { | |
return { | |
action: "print", | |
string, | |
next: pure, | |
} | |
} | |
// A pure program that simply returns a value. | |
function pure (value) { | |
return { | |
action: "pure", | |
value, | |
} | |
} | |
function interpret (program) { | |
switch (program.action) { | |
case "read": | |
const input = readline.question("") | |
return interpret(program.next(input)) | |
case "print": | |
console.log(program.string) | |
return interpret(program.next(null)) | |
case "pure": | |
return program.value | |
} | |
} | |
// Bind two programs together. Return a new program which is equivalent to | |
// running the first program and feed its return value to the second one. | |
function bind (program, next) { | |
switch (program.action) { | |
case "pure": | |
return next(program.value) | |
default: | |
return { | |
...program, | |
next: (val) => bind(program.next(val), next) | |
} | |
} | |
} | |
const number = 42; | |
const game = | |
bind(print("Enter a guess"), _ => { | |
return bind(read(), (input) => { | |
const guess = Number(input) | |
if (guess === number) { | |
return print("Congratulations! You found it.") | |
} else if (guess < number) { | |
return bind(print("Higher"), _ => game) | |
} else if (guess > number) { | |
return bind(print("Lower"), _ => game) | |
} else { | |
return print("Just numbers, please.") | |
} | |
}) | |
}) | |
// To execute the program, we would just have to call: | |
// interpret(game) | |
// For later | |
export default game |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment