Skip to content

Instantly share code, notes, and snippets.

@safareli
Last active October 6, 2016 06:46
Show Gist options
  • Save safareli/13748ab3618d5a6084addc5b36f63520 to your computer and use it in GitHub Desktop.
Save safareli/13748ab3618d5a6084addc5b36f63520 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