Hacker News new | ask | show | jobs
by nickthemagicman 4606 days ago
That looks sweet but I can't help but wonder: How are those implemented internally? It seems like it would be loops?
1 comments

It depends on the language and library. You can implement them, or any loop for that matter, or any computing construct furthermore, with function application alone. This is what the lambda calculus [1] and combinatory logic [2] are all about.

In actual languages, it depends. In languages without tail-call optimization [3] (i.e. Python and JS), a loop is probably the most efficient way. But with it, it's not particularly important. In a purely functional language, loops indexed by mutable variables aren't on the table, so you have to go the recursive route.

A basic flatmap on a list is pretty easy to define without for loops in JS (although I would definitely recommend just using a library for all sorts of practical concerns):

    function flatMap(list, f) {
        if (list.length) {
            return f(list[0]).concat(flatMap(list.slice(1), f));
        } else {
            return [];
        }
    }

    flatMap([1,2,3], function (x) { return [x, x]; });
    // -> [1, 1, 2, 2, 3, 3]
[1] http://en.wikipedia.org/wiki/Lambda_calculus

[2] http://en.wikipedia.org/wiki/Combinatory_logic#Combinatory_l...

[3] http://en.wikipedia.org/wiki/Tail_call