In this article, you will learn what function paradigms are and how to program functionally in Python. You will also learn about list derivations and other forms of derivations.

Function paradigm

In the imperative paradigm, tasks are accomplished by giving the computer a series of instructions and then executing them. When these instructions are executed, certain states can be changed. For example, suppose you initially set A to 5 and then change the value of A. Then you change the state of A in the sense of the internal values of the variable.

In the functional paradigm, instead of telling the computer what to do, you tell it what the thing is. What is the greatest common divisor of a number, what is the product from 1 to n, and so on.

Therefore, variables cannot change. Once you set a variable, it stays that way forever (note that in purely functional languages, they are not variables). Therefore, functional programming has no side effects. A side effect is when a function changes something other than itself. Let’s look at some examples of typical Python code:

The output of this code is 5. In functional paradigms, changing variables is a big no-no, as is having the ability to influence things outside of its scope. The only thing a function can do is evaluate something and return it as a result.

Now you might be thinking, “No variables, no side effects? Why is that good? “That’s a good question, and I’m sure most people are wondering.

If you call a function twice with the same arguments, you are guaranteed to return the same result. If you’ve studied mathematical functions, you know this benefit. This is called referential transparency. Since functions have no side effects, if you’re building a program that evaluates something, you can speed it up. If every call to func(2) returns 3, we can store it in a table, which prevents the program from running the same function twice.

In general, in functional programming, we don’t use loops. We use recursion. Recursion is a mathematical concept that usually means “self-invocation.” Use a recursive function that calls itself repeatedly as a child function. Here’s a good example of a recursive function in Python:

Some programming languages are also lazy. This means they don’t calculate or do anything until the last second. If you write some code to perform 2 + 2, the function will only evaluate when you really need to use the result. We’ll explore inertia in Python shortly.

Map

To understand, let’s look at what an iteration is. The usual objects that can be iterated over are lists or arrays, but Python has many different types that can be iterated over. You can even create your own objects, which can be iterated over by implementing magic methods. Magic methods are like an API to help your objects become more Pythonic. You need to implement two magic methods to make an object iterable:

The first magic method, “__iter__”, returns the iterator, which is usually used at the beginning of the loop. __next__ “returns the next object.

Let’s quickly go to a terminal and call the code above:

The run will print

In Python, an iterator is an object with only __iter__ magic methods. This means that you can access locations in an object, but you cannot traverse the object. Some objects will have the magic method __next__ instead of the __iter__ magic method, such as collections (discussed later in this article). For this article, we’ll assume that everything we touch is an iterable object.

Now that we know what an iterable is, let’s go back to the map function. The map function allows us to apply functions to each item in iterable. The Map requires two inputs, the function to be applied and the iterable.

Suppose we have a list of numbers that looks like this:

If we want to square each number, we can write the following code:

Functional functions in Python are lazy. If we do not use “list”, this function stores the definition of iterable, not the list itself. We need to explicitly tell Python to “make it a list” for us to use.

It’s a little strange to suddenly go from non-lazy evaluation to lazy evaluation in Python. If you think more in a functional way of thinking than in an imperative way, then you will eventually get used to it.

Now it’s nice to write a normal function like “square(num)”, but it’s not right. We have to define a complete function to use it in the map, right? Well, we can use lambda (anonymous) functions to define a function in a map.

Lambda expressions

A lambda expression is a one-line function. For example, this lambda expression squares a given number:

Let’s run it:

Doesn’t that look like a function?

Well, it’s a little confusing, but it’s explainable. We assign something to the variable “square”. How about this:

Tell Python that this is a lambda function and that the input is called x. Anything after the colon is what you did to the input, and it automatically returns the result.

To simplify our Square program to just one line of code, we can do this:

So in a lambda expression, all the arguments are on the left, and whatever you want to do with them is on the right. It’s a bit messy. But the truth is, there’s a certain amount of fun in writing code that only other functional programmers can read. Also, it’s cool to take a function and turn it into a line of code.

Reduce

Reduce is a function that turns an iteration into a thing. In general, you can use the reduce function to perform calculations on a list to reduce it to a single number. Reduce looks like this:

Lambda expressions are often used as functions.

The product of lists is the multiplication of each individual number. To do this you will write the following code:

But with reduce you can write:

Get the same functionality, the code is shorter, and cleaner when using functional programming. (note: reduce is no longer a built-in function in Python3 and needs to be imported from the functools module)

Filter

The filter function takes an iterable approach and filters out everything you don’t need in that iterable.

In general, a filter requires a function and a list. It applies the function to each item in the list and does nothing if the function returns True. If False is returned, the item is removed from the list.

The syntax is as follows:

Let’s look at a small example, without filter we would write:

Using filter, you can write:

Python is an evolving and popular language that is constantly being updated. In the study, it is suggested to find some study partners to study and discuss together, the effect is better. If you want to learn Python, welcome to join the Python Learning Exchange Group (627012464) to urge and learn together. There are development tools, lots of dry goods and technical information sharing!

Higher-order functions

Higher-order functions can take functions as arguments and return functions. A very simple example is as follows:

The second return function example:

I began by saying that purely functional programming languages have no variables. Higher-order functions make this easier.

All functions in Python are first-class citizens. A first-class citizen is defined as having one or more of the following characteristics:

Created at run time

Assign variables or elements in a data structure

Passed as an argument to a function

Return as the result of the function

All functions in Python can be used as higher-order functions.

Partial application

Partial Applications (also known as closures) are a little weird, but very cool. You can call a function without providing all the parameters you need. Let’s see this in an example. We want to create a function that takes 2 arguments, a base and an exponent, and returns the base of the exponent, as follows:

Now we want a special square function that uses the power function to square the number:

That works, but what if we want a cube feature? Or what about the power of the fourth? Can we keep writing them down? Well, you can. But programmers are lazy. If you repeat the same things over and over again, it shows that there is a faster way to speed things up, which will keep you from repeating them. We can use closures here. Let’s look at an example of the square function using a closure:

Isn’t that cool! We can use only one argument to call a function that requires two arguments.

We can also use a loop to generate a power function that implements powers from the cube all the way up to 1000.

Functional programming is not Pythonic

As you may have noticed, a lot of what we want to do in functional programming revolves around lists. With the exception of reduce functions and closures, all the functions you see generate lists. Guido doesn’t like functional expressions in Python because Python already has its own way of generating lists.

If you write “import this” in Python’s interactive environment, you will get:

This is the Zen of Python. This is a poem about what Pythonic means. The sections we want to cover are:

Preferably only one — obvious way to do it. Hence, it should be one — and preferably only one — obvious way to do it.

In Python, maps and filters can perform the same operations as list derivations (discussed below). This breaks a rule of Python Zen, so these parts of functional programming are not considered “pythonic.”

Another topic is Lambda. In Python, a lambda function is an ordinary function. Lambda is syntactic sugar. The two statements are equivalent.

A normal function can do everything a lambda function can, but it cannot work the other way around. Lambda functions cannot do all the things that ordinary functions can.

This is a short argument for why functional programming does not fit well into the Python ecosystem as a whole. You may have noticed that I mentioned list derivations earlier, and we’ll discuss them now.

The list of deduction

Earlier, I mentioned that anything you can do with a map or a filter, you can derive with lists. List derivation is a way of generating lists in Python. Grammar is:

Let’s square each number in the list, for example:

We can see how the function applies to each item in the list. How do we apply filter? Take a look at the previous code:

We can convert this to a list derivation like this:

Lists support statements like if. You no longer need to apply a million functions to something to get what you want. In fact, if you want to try to generate some kind of list, it’s much clearer and easier to use list derivation. What if we wanted to square every number in the list below zero? With lambda, map, and filter you would write:

It seems very long and complicated. By list deduction, it simply:

List derivation applies only to lists. Map,filter works for any iterable object, so what’s the use of that? You can use any derivation for any iterable you encounter.

The other is

You can create a derivation for any iterable.

You can use derivation to generate any iterable object. Starting with Python 2.7, you can even generate dictionaries (hashMaps).

If it is iterable, it can be generated. Let’s take a look at the last group.

A set is a list of elements in which no element is repeated twice.

The elements in a set have no order.

You might notice that a set has the same curly braces as a dict. Python is very clever. It knows whether you are writing a dict derivation or a set derivation based on whether you provide a value for dict.

conclusion

Functional programming is beautiful and pure. Functional code can be clean, but it can also be messy. Some Python programmers dislike functional programming in Python. But I think you should use the best tools for solving problems.