6 ms·
Disclaimer: as a Clojure developer and functional programming evangelist, I do not want to be too critical of this article. It's a really great post about some
by whalesalad 9y ago
Disclaimer: as a Clojure developer and functional programming evangelist, I do not want to be too critical of this article. It's a really great post about some incredibly valuable and advanced Clojure features.
That being said, it really bothers me when functional programming evangelists write out such horrible Python code examples. It makes Python look like it's not a functional language. It perpetuates the idea that Python won't let you write elegant and stateless programs that behave in a functional manner.
If the author had not mentioned Python and had instead used it as pseudocode to represent the entirely non-functional way to write something, I would have been okay with it. But calling out Python specifically is just incorrect!
I have rewritten the code in a very pythonic manner that illustrates the functional capabilities of the language:
even = lambda x: x % 2 == 0
# alternatively, depending on your religious beliefs:
def even(x): return x % 2 == 0
def process(seq):
return sum(x + 1 for x in seq if even(x))
Note the (parens) for the comprehension instead of [brackets], which creates a generator. The above code is lazy (in Python 3)!
And if we fire up a python repl and play around:
In [2]: process(range(10))
Out[2]: 25
I really love Clojure and use it daily, but I find the Python version to be far more legible. It reads more like english.
Anyway, the moral of the story here is that you can do immutable/functional programming with regular ol' Python.
- projectorlochsa 9y agoyou can remove the extra parentheses after sum.
- mod 9y agoI think the inner set is supposed to be brackets []. It's a comprehension.
- whalesalad 9y agoThe above commenter is correct. You can use parens in place of brackets to utilize a generator.
- nimish 9y agoNamed lambdas are discouraged as un-Pythonic for what it's worth. The other point in the article was that your process has now hard-coded even and sum, and composing them in python is a bit unwieldy. I've run into a number of cases where it's just easier in python to write out the loops than string comprehensions or map/filter/reduces together because there's no threading macro or haskell's functional apply operator.
- whalesalad 9y agoYou can compose it all together in a relatively straightforward manner using functions in the stdlib. I agree that it is nicer with a threading macro, but is this so bad? def even(x): return x % 2 == 0 def inc(x): return x + 1 def process(seq): return sum(map(inc, filter(even, seq)))
- emidln 9y agoYou can also easily write pipeline() (which is just a reduction over callables inside a lambda[0]) such that: process = pipeline(partial(filter, even), partial(map, inc), sum) process(some-iterable) I'll grant that it's not syntactically ideal (this is the tradeoff the thrush combinator (pipeline) running as a function instead of working as a macro. The benefit of being able to follow down the program as it works remains. (def process [xs] (->> xs (filter even?) (map inc) (reduce +))) (process some-iterable) If you compare a function-based approach[1] (instead of a macro) you might get: (def process (pipeline (partial filter even?) (partial map inc) (partial reduce +))) process(some-iterable) [0] A sample Python definiton (python doesn't have compose to reverse): def pipeline(*fns): return reduce(lambda f, g: lambda *xs, **ys: g(f(*xs, **ys)), fns) [1] A clojure implementation: (defn pipeline [& fs] (apply compose (reverse fs)))
- lvh 9y agoThat's true, but a bit of an unfortunate example since the point of the article is to demonstrate transducers, and instead this demonstrates a bunch of chained collection functions.
- Veedrac 9y agoPlease use def over lambda when feasible (which is most of the time); using lambda needlessly hurts debugability and saves a total of three characters. def even(x): return x % 2 == 0
- flavio81 9y agoYes but lambda allows some versatility, for example (excuse my Python, it is a bit rusty): formulas = { 'sum': lambda x,y: x+y, 'subst': lambda x,y: x-y, 'mult': lambda x,y: x*y, 'pow': lambda x,y: x**y } def apply_operator(operation_name, x, y): operation=formulas[operation_name] return operation(x,y) Using "def"s there would kill readability and easiness of coding.
- tobik 9y agoBad example :) Most simple uses of lambda like this can be substituted with functions from the operator module: import operator formulas = { 'sum': operator.add, 'subst': operator.sub, 'mult': operator.mul, 'pow': operator.pow }
- flavio81 9y agoI thank you for this example. If the operator definitions are not trivial and you want to keep them well mantained, then your example is very good. However, what I meant was that for fast, quick coding, if your 'operator' function is really simple, then lambda fints perfectlu. I know the Zen of Python says: "There should be one—and preferably only one—obvious way to do it", but i don't align to that principle. I think there should be more than one way to do something, and one should choose one that fits the best.
- owebmaster 9y agoIt is not about char length. The first is an expression while the second is a statement. I find it easy to debug code with expressions rather than statements, could you clarify why the first way would be worse for debugability?
- specialp 9y agoI get what you are saying, but I think the author was not trying to do that. The example was meant to show the imperative approach which is not necessarily the best approach in Python either. They said so much in the paragraph before the example. Yes, Python was used and is used often to show imperative examples. Python is used in these examples because it is also dynamically typed, and understood by a lot of programmers. The reason it is not given in Clojure is that it is pretty hard to make imperative examples in Clojure. Also, coming from Ruby, the way the "process" function was posted is unfortunately the way many Ruby programmers would do it despite access to filter, map and blocks.
- azag0 9y agoOr, with a little setup, the Closure snippet (def s (range 0 10)) (reduce + (map inc (filter even? s))) can be turned into Python's from functools import reduce from operator import add def inc(x): return x + 1 def even(x): return x % 2 == 0 s = range(0, 10) reduce(add, map(inc, filter(even, s))) Everything's lazy in there. It's just... not very Pythonic.
- jerf 9y ago"It makes Python look like it's not a functional language. It perpetuates the idea that Python won't let you write elegant and stateless programs that behave in a functional manner." I suggest Go for this use case. It's easy enough to read for this sort of thing even if you don't know the language, easy to link to running examples on the playground, and nobody will accuse you of showing Go off in a worse light than is called for because the Go equivalent of the imperative example shown really is the Go way to do it. Go is just about the most aggressively non-FP language out there today, making even Python look friendly to FP programming, despite the fact it has closures.
- eliben 9y agoThanks for the comment. I totally agree that Python can express this with its functional primitives as well. I was simply using it to show an "imperative style", and Python is my favorite executable pseudo-code. [P.S: I'm a Python core developer and long-time user; calling Python out is really, really not my thing!]
- deleted 9y ago[deleted]
- willtim 9y ago> "you can do immutable/functional programming with regular ol' Python" One cannot easily and safely do functional programming in Python due it's imperative semantics. For example variables are captured as mutable references and even a list comprehension will mutate its bindings. If you want to do serious functional programming, use Clojure, Haskell and/or OCaml. Edit: to the downvoters, it's about using the right tool for the job.
- didibus 9y agoPython is multi-paradigm, I think everyone would agree, but I think they removed the ability to do this with function composition like map, reduce and filter in v3 no? Specifically in favor of list comprehensions and generators? Anyways, if you do it with list comprehensions in Clojure it would look like this: (apply + (for [x (range 10) :when (even? x)] (inc x)))
- eliben 9y agoIn Python 3 functions like reduce were moved to the functools module, not removed from the language.
- bad_user 9y ago> perpetuates the idea that Python won't let you write elegant and stateless programs that behave in a functional manner Well, in my opinion Python really does not let you write elegant and stateless programs that behave in an FP manner. The sample you've chosen in particular is all fine, except that `lambda` expressions are almost never used, due to Python not being expression oriented, so there isn't much you can express with a `lambda`. You might find your `for x in seq if even(x)` expression elegant, but it is preceded by a `return`. Python is a statement / side effects oriented language and even in your one liner, it shows. Oh, and given that a Python "generator" is like Java's Iterable / Iterator, that's not FP either, although you can argue that the mutation can be localized (e.g. in your `sum` example), but you have to be careful about it. And if you'll take a look at the whole Python ecosystem, there's not much FP in it to be honest. I mean, seriously, out of all the mainstream languages, I can't think of a worse language to do FP than Python, except for C maybe,
- merlincorey 9y agoCheck out toolz[0] for a Clojure inspired FP toolkit in Python. [0] http://toolz.readthedocs.io/en/latest/ http://toolz.readthedocs.io/en/latest/
- blowbaybestban 9y agofor full on functional style, as far as I am concerned, process() should be recursive (without all the overhead that implies in an imperative language). I'm being sarcastic because I don't like the list comprehension syntax.