DEV Community

loading...

Discussion on: Why I don't believe in pure functional programming anymore

yujiri8 profile image
Ryan Westlund Author

One more example -- there's no "reduce" comprehension in Python. So you're back to loops there. For the specific case of adding, they give you a sum function. But you don't have the thing that would let you write your own (at least in a functional style).

Huh? I just mentioned functools.reduce. It works with any function or lambda. What does Ruby's reduce get that Python's doesn't?

Thread Thread
yujiri8 profile image
Ryan Westlund Author

Oh - is it the ability to reduce from the outer function (halting iteration)?

I guess that could be useful... in some really obscure situation or something...

Thread Thread
johncip profile image
jmc • Edited

Oh I just meant Python's comprehensions -- they cover some of the places you'd use map & filter, but there's no comprehension for going down to a scalar, AFAIK. (That said, since reduce can be used to build collections, list / dict / set comprehensions do end up overlapping with it.)

And to be clear, when I said "you're back to loops" I meant for the places where you wouldn't bother to create a named inner function, or to compose named functions before calling them. (It's not that you don't have options, but I'd argue that they're not idiomatic or lightweight.)

What does Ruby's reduce get that Python's doesn't?

While reduce works the same everywhere, it's most useful in languages with anonymous inner functions. It's true of higher-order functions in general, not just reduce.

Ruby goes a step further by providing a shorthand syntax for doing this (but is not unique there -- Clojure has the #() shorthand, and JS has ->).

FWIW, since you mentioned it -- I've only felt the need to halt from inside a reducer function in Clojure. I forget why, but it probably had to do with starting from an infinite stream. It'd be an optimization to prevent the creation of intermediate collections.