Some functional programming tricks in Python
In this article, I would like to talk about what came to Python from functional programming languages. Interested, I ask for cat.
It is easy and simple: instead
l =  for x in range(10): if x % 2 == 0: l.append(x)
l = [x for x in range(10) if x % 2 == 0]
Short and clear.
In Haskell, the same thing will look like this:
let l = [x | x <- [0..10], x `mod` 2 == 0]
Suppose we are writing a graphical interface and we have a button (** kwargs) function, where valid named arguments are: text for text, width for width, height for height and command for a callback function:
def callback(event): print("Button pressed") button(text="Press me", width=32, height=16, command=callback)
Notice how small our callback is, is it really easy to push it with an argument? Can! Lambdas will help us:
button(text="Press me", width=32, height=16, command=lambda x: print("Button pressed"))
Clean and easy!
In Haskell, passing a function as an argument occurs at every step, for example, the map function takes a function and a list and returns a list for each element of which this function was applied:
map (\x -> x+1) [1..10]
In Python, this is:
map(lambda x: x+1, [x for x in range(1, 10)])
True, there is no map in Python.
upd: map is!
Currying is when we pass one or more arguments to an old function to get a new one that takes the rest (thanks AnutaU for a more precise definition). For example: print is a function (I use Python 3), it has a named argument end - the end of the line, by default it is "\ n". I want not to jump to a new line, then I write
Let's make a printf function that will not jump to a new line
def printf(*args, **kwargs): kwargs["end"] = "" print(*args, **kwargs)
Sloppy, it is possible and easier:
from functools import partial printf = partial(print, end = "")
Here it is, currying - we say what we want
exactly the same, but with mother-of-pearl buttonsprint function, but so that end is equal to "". Everything is simple.
And again Haskell: we have a + function that takes two arguments, we say:
let plusTwo = (+2)
I now have a function that adds 2 to a single argument.
I have everything, if you know what else is in Python from functionalism - I ask in the comment.
Questions and feedback there too.