Книга: Learning Concurrency in Python
Назад: Installation and official docs
Дальше: Output

Simple example

Let's take a look at a very simple example to show you how you can write functional programs using the PyFunctional module. This will act as a toe-dipping example that should hopefully give you the gist of some of the basic things you can accomplish with the PyFunctional module.

In this example, we'll leverage seq, which acts as the stream object with which we can iterate and manipulate. We'll first map this sequence using a lambda function that doubles every value. After this, we'll filter for values where x is greater than 4, and finally, we'll reduce the sequence into a summation of all the remaining values:

from functional import seq

result = seq(1, 2, 3, 4)\
.map(lambda x: x * 2)\
.filter(lambda x: x > 4)\
.reduce(lambda x, y: x + y)
print("Results: {}".format(result))
Назад: Installation and official docs
Дальше: Output