Last active
May 29, 2020 07:30
-
-
Save WreckedAvent/9ba4c0358022390521c709f05fb35178 to your computer and use it in GitHub Desktop.
sweet js ML-style let bindings for auto-curried functions
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
// Auto curried function definitions using let, like ML | |
// | |
// Examples: | |
// let add x y = x + y | |
// let map f ctx = tx.map(f) | |
// NOTE: requires auto-curried function macro: https://gist.github.com/WreckedAvent/9aa698d3e9e6a46c5c62c1e266c95f20 | |
syntax let = ctx => { | |
const ids = [] | |
let ret = null | |
let body = null | |
// start parsing our context | |
for (let value of ctx) { | |
// we want to capture how many identifiers we have to determine what kind of let we have | |
if (value.isIdentifier()) { | |
ids.push(value) | |
} | |
if (value.isPunctuator()) { | |
// if we run into a punctuator (like =) after we got one identifier, that's a normal let, so | |
// we don't need to parse anything more | |
if (ids.length === 1) break | |
// otherwise we have more than one identifier, so parse it as a function body | |
else { | |
// ctx.mark() | |
// var next = ctx.next().value | |
// https://github.com/sweet-js/sweet.js/pull/565 | |
// right now, just assume it's an expression - see above pull for when | |
// we can lookahead and see if it's also a block | |
body = ctx.expand('expr').value | |
break | |
} | |
} | |
} | |
// normal let | |
if (ids.length === 1) { | |
ctx.reset() | |
return #`let ${ctx}` // just pass through normal compilation | |
} | |
// in function let form, the first identifier is the name of our let function | |
let [name, ...others] = ids | |
// function let structure | |
return #`let ${name} = fun ${others} { ${body} }` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment