Skip to content

Instantly share code, notes, and snippets.

@MarkusPfundstein
Forked from safareli/tailRec.js
Created October 6, 2016 06:46
Show Gist options
  • Save MarkusPfundstein/46a354a6a471817971b6098312f41ec9 to your computer and use it in GitHub Desktop.
Save MarkusPfundstein/46a354a6a471817971b6098312f41ec9 to your computer and use it in GitHub Desktop.
const tailRec = (f) => (a) => {
let v = f(a)
while (!v.done) {
v = f(v.value)
}
return v.value
}
const done = (v) => ({ value: v, done: true })
const next = (v) => ({ value: v, done: false })
const sum = (n) => {
const go = ({ i, acc }) => i == 0 ? done(acc) : next({ i: i-1, acc: acc+i })
return tailRec(go)({i:n, acc:0})
}
console.log(sum(100000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment