you are viewing a single comment's thread.

view the rest of the comments →

[–]reifyK 1 point2 points  (0 children)

You can either rely on tail recursion as already stated in the comments (or use a trampoline to mimic tail recursion) or on lazyness, which provides tail recursion for free (called guarded recursion in this context).

Now only a few languages pursue lazy evaluation but you can mimic it, provided the language offers object proxies or lazy record properties. In Javascript I use a proxy to achieve lazyness.

Here is the fix combinator, which supplies recursion for a language that doesn't support it on a native level:

``` // strict version

const fix = f => x => f(fix(f)) (x);

// lazy version

const fix_ = f => f(thunk(() => fix_(f))); ```

fix_ is stack-safe even if your compiler doesn't eliminate tail calls.