by codedokode · 5y ago · 0 comments
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.
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.
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.
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.