📜 ⬆️ ⬇️

Some functional programming techniques in Python

Hi, Habr!
In this article, I would like to talk about what came to Python from functional programming languages. Interested please under the cat.


List generators


It's easy and simple: instead of


l = [] for x in range(10): if x % 2 == 0: l.append(x) 

we are writing


 l = [x for x in range(10) if x % 2 == 0] 

Short and clear.


How it works in functional languages

In Haskell, the same thing looks like this:


 let l = [x | x <- [0..10], x `mod` 2 == 0] 

Lambda


Suppose we write a graphical interface and we have a function button (** kwargs), where valid named arguments are: text is for text, width is for width, height is for height, and command is for callback function:


 def callback(event): print("Button pressed") button(text="Press me", width=32, height=16, command=callback) 

Pay attention to how small our callback is, can it really be pushed through with an argument? Can! We will help lambda:


 button(text="Press me", width=32, height=16, command=lambda x: print("Button pressed")) 

Clean and easy!


How it works in functional languages

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, to which each element 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!


Carring


Currying (currying) is when we pass one or more arguments to an old function in order to get a new one that accepts the rest (thanks to 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 move to a new line, then I write


 print(str, end="") 

Let's do a printf function that will not move 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 we want exactly the same but with pearl buttons print function, but so that end is "". It's simple.


How it works in functional languages

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 there is in Python from the functional area - please in the comments.
Questions and reviews there too.


')

Source: https://habr.com/ru/post/336160/


All Articles