3 ms·
Is there a blend between the two? I really like loops...
by nickthemagicman 13y ago
Is there a blend between the two? I really like loops...
- acjohnson55 13y agoLet go of your loops and learn to map, flatMap, and fold! Once I really figured out how to use those effectively, I've written far few indexed for loops. I tried to explain this philosophy on a recent and unheralded SO answer: http://stackoverflow.com/questions/19720830/is-it-safe-to-modify-an-array-while-looping-it/19721042#19721042 http://stackoverflow.com/questions/19720830/is-it-safe-to-mo...
- nickthemagicman 13y agoThat looks sweet but I can't help but wonder: How are those implemented internally? It seems like it would be loops?
- acjohnson55 13y agoIt 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 http://en.wikipedia.org/wiki/Lambda_calculus [2] http://en.wikipedia.org/wiki/Combinatory_logic#Combinatory_logic_in_computing http://en.wikipedia.org/wiki/Combinatory_logic#Combinatory_l... [3] http://en.wikipedia.org/wiki/Tail_call http://en.wikipedia.org/wiki/Tail_call