Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active May 7, 2017 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/538b8474c6a5f838f7186b111e7ec882 to your computer and use it in GitHub Desktop.
Save JadenGeller/538b8474c6a5f838f7186b111e7ec882 to your computer and use it in GitHub Desktop.
Lambda Calculus w/o Parenthesis
//// 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