Python

Although Python is not a functional programming language (it is an imperative programming language), it supports many valuable functional programming tools. Python provides three built-in functions and lambda expressions to support functional programming.

Anonymous functions

Python allows anonymous functions to be created using the lambda keyword. Anonymity, as the name implies, does not have a name, that is, it does not need to be declared in a standard way, for example, using def plus the function name. A complete lambda “statement” represents an expression whose body must be on the same line as the declaration. The syntax is as follows:

lambda [arg1[, arg2, ... argN]]: expression

Arguments are optional, and if they are used, they usually appear in expressions as well.

Note: lambda expressions return callable function objects. The lambda expression itself is a function that defines the input (to the left of the colon) and the output (to the right of the colon). The function has no name, but we can assign it to a variable.

Simple addition functions, for example. We usually write it like this:

def add(x, y):
    return x+y
Copy the code

Lambda expressions are written like this:

lambda x, y : x + yCopy the code

Lambda x, y: x + y we can assign lambda x, y: x + y to f and pass the argument to f:

> > > f = lambda x, y, x + y > > > at 0 f x10377f320 > > > > f (10, 8) - 2 > > > f (12, 100) 112 > > > f (- 33-22) - 55Copy the code

As you can see, f is indeed a function that takes two arguments and returns the sum of the two arguments, equivalent to the add function above.

Higher-order functions

Higher-order functions are called higher-order functions. A function is a higher-order function if it accepts a function as its input parameter or if its return value contains a function.

Python has three higher-order functions built in to support functional programming: filter(), map(), and reduce().

filter()

Filter (function, sequence) returns a sequence containing all elements in the input sequence that return true when function(item) is called.

The working process of Filter () is shown as follows:

how the filter() built-in function works

Here’s an example:

>>> def f(x): return x % 3 == 0 or x % 5 == 0
...
>>> filter(f, range(2, 25))
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]
Copy the code

Because filter() contains the function f() in its input arguments, filter() is a higher-order function. The above example returns a list of numbers from 2 to 24 that are divisible by 3 or 5.

Of course, anonymous function lambda expressions can also be used:

>>> filter(lambda x : x % 3 == 0 or x % 5 == 0, range(2, 25))
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]
Copy the code

Or use list generation:

>>> [x for x in range(2, 25) if x % 3 == 0 or x % 5 == 0]
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]
Copy the code

map()

Map () is similar to filter() in that it can also process sequences through functions. Map () “maps” the function call to each element of the sequence and returns a list of all the returned values.

The workflow of MAP () is shown below:

How the map() built-in function works

Here’s an example:

>>> def cube(x): return x**3 ... >>> Map (Cube, range(1,11)) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]Copy the code

In the above example, we call Cube () for each number between 1 and 10 and place the return value (x ^ 3) into the list.

Lambda expressions:

>>> map(lambda x : x**3, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Copy the code

List generation:

>>> [x**3 for x in range(1, 11)]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Copy the code

Note: Map () can also process multiple sequences.

>>> map(lambda x, y: x + y, [1, 3, 5], [2, 4, 6])
[3, 7, 11]
>>> map(lambda x, y: (x+y, x-y), [1, 3, 5], [2, 4, 6])
[(3, -1), (7, -1), (11, -1)]
>>> map(None, [1, 3, 5], [2, 4, 6])
[(1, 2), (3, 4), (5, 6)]Copy the code

The working process is as follows:

How the map() built-in function works with > 1 sequence

reduce()

Reduce (function, sequence) returns a single value, which is constructed by calling function with the first two elements of the sequence, then with the return value and the third argument, and so on.

The working process of reduce() is as follows:

How the reduce() built-in function works

For example, the following program calculates the sum of integers from 0 to 5:

>>> def add(x, y): return x+y
...
>>> reduce(add, range(0, 5))
10
Copy the code

In fact reduce() performs the following operation:

((((0 + 1) + 2) + 3) + 4) = = > 10Copy the code

Lambda expressions:

reduce(lambda x, y : x + y, range(0, 5))Copy the code

Partial function

Partial functions solve the problem that if we have a function with multiple parameters, we want to fix the values of some of the parameters (similar to the default values).

Here’s an example:

The int() function converts a string to an integer. When only a string is passed in, the int() function converts to decimal by default:

>>> int('11111')
11111Copy the code

But the int() function also provides an additional base argument (the default is 10). If we pass in the base argument, we can do the n-base conversion:

>>> int('11111',8)
4681
>>> int('11111',base=16)
69905
Copy the code

Int (x, base=2); int(x, base=2); int(x, base=2);

def int2(x, base=2):
    return int(x, base)
Copy the code

Thus, we can easily convert binary:

>>> int2('1000000')
64
>>> int2('1010101')
85
Copy the code

Functools.partial is used to create a partial function. Instead of defining int2(), we can create a new function int2 with the following code:

>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2('11111')
31
>>> int2('10000')
16Copy the code

Functools. partial is a function whose parameters are fixed (that is, set defaults) and returns a new function that is easier to call.

Note that the new int2 function above simply resets the base argument to its default value of 2, but other values can also be passed in when the function is called:

>>> int2('11111',base=10)
11111
>>> int2('11111',base=8)
4681Copy the code

reference

  • Python Core Programming
  • Python Official Documentation
  • Python tutorial by Liao Xuefeng