Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

For me, code with reduce is less readable than a loop. With loop everything is obvious, but with reduce you need to know what arguments in a callback mean (I don't remember), and then think how the data are transformed. It's an awful choice in my opinion. Good old loop is so much better.


I disagree entirely. In most imperative programming languages, you can shove any sort of logic inside a loop, more loops, more branches, creating new objects, its all fair game.

Fold and map in functional languages are often much more restrictive in a sense. For example, with lists, you reduce down a collection [a]->a to a single object, or produce another collection with a map [a]->[a]. So map and fold etc are much more restrictive. That's what makes it clearer.


if you are used to imperative programming, then yes.

But in a for loop anything can happen- from a map to a reduce to a mix, to whatever convoluted logic the dev comes up with.


Technically you can implement map as reduce ;)

But yes - for me

    (defn factorial [n]
      (reduce * (range 1 (inc n))))
is slightly more readable than

    def factorial(n):
        result = 1
        for i in range(2,n+1):
           result *= i
        return result
I mean in this case the name kinda makes it obvious anyway :)

If the operation is conceptually accumulating something over the whole collection and if it's idiomatic in the language I'm using - I will use reduce. Same with map-y and filter-y operations.

But if I have to do some mental gymnastics to make the operation fit reduce - for loop it is. Or generator expression in case of python.


Indeed. I rarely encounter basic loops in code reviews now, so seeing one is definitely a small alert to do an extra thorough review of that part.


And it is usually very easy and straightforward to see what is going on inside.


It can definitively happen, but I think more times than not the others are more readable.

To be honest this seems to be a familiarity thing > but with reduce you need to know what arguments in a callback mean

If I didn't know for it would be mind boggling what those 3 things, separated by semicolons, are doing It doesn't look like anything in the usual language(s) they're implemented. It's the same with switch.

The only thing both of them have, for and switch, and helps, is that languages that offer it and aren't FP usually use the same *C* form across all, whereas reduce's args and the callback args vary a bit more between languages, and specially between mutable and immutable langs.

I still prefer most of the time the functional specific counterparts.


Guido?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: