Last active
May 7, 2017 09:13
-
-
Save JadenGeller/538b8474c6a5f838f7186b111e7ec882 to your computer and use it in GitHub Desktop.
Lambda Calculus w/o Parenthesis
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
//// Implementation | |
OPEN = Symbol("open") | |
CLOSE = Symbol("close") | |
function run(program) { | |
function applyUntilClose(continuation = x => x) { | |
function iter(f) { | |
if (f === OPEN) { | |
return applyUntilClose(r => iter(r)) | |
} else if (f == CLOSE) { | |
throw new Error("Unexpected empty grouping") | |
} else { | |
return function (x) { | |
if (x === OPEN) { | |
return applyUntilClose(r => iter(f(r))) | |
} else if (x === CLOSE) { | |
return continuation(f) | |
} else { | |
return iter(f(x)) | |
} | |
} | |
} | |
} | |
return iter; | |
} | |
return program(applyUntilClose())(CLOSE) | |
} | |
//// Example | |
// Boring helpers: | |
let min = x => y => x < y ? x : y; | |
let plus = x => y => x + y; | |
let square = x => x * x; | |
// Cool part: | |
// equivalent to `square (plus (min 2 (plus 1 2)) 5)` | |
let program = x => x(square)(OPEN)(plus)(OPEN)(min)(2)(OPEN)(plus)(1)(2)(CLOSE)(CLOSE)(5)(CLOSE) | |
console.log(run(program)) // -> 49 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment