Code With Functional Programming
00:00 Welcome to this lesson, where you’ll explore the fascinating world of functional programming and pure functions. As the name suggests, functional programming relies on functions to perform tasks, but what sets it apart from other programming paradigms is the use of pure functions. Pure functions are functions that don’t change the program’s state.
00:23 This means that when you call the function with a specific input, it always returns the same output. It doesn’t modify any variable outside of its scope or depend on any external state. Now, you might be wondering, why is this important? Well, pure functions make your code more predictable, testable, and easier to reason about. When you use pure functions, you can be confident that your program will behave consistently.
They’re basically nameless functions that you use when you need a function, but not for a very long time. You just need them for a short period of time. They’re also called lambda functions, and
reduce() are also functions that are really important.
The function on the right is not a pure function because it uses a global variable named
total that is set to
0. When the
add_numbers() function is called with two variables,
b, it adds them together, updates the global
total variable, and then returns it. Right here, because the function modifies the global state—and by that, I mean the value of the
total variable—calling it twice with the same input won’t always produce the same result. The output will depend on the current state of the
On the second iteration, the
add_numbers() function adds the sum of
2 to the current value of the
total variable, which is
3 from the previous iteration, resulting in a return value of
6. In conclusion, the
add_numbers() function you just explored is not a pure function because it modifies the global state.
You’ll hear more about this shortly. On the other hand, the function on the left is a pure function, since it does not modify any global variable and always returns the same output for identical inputs. As you can see, the first time you run the function with inputs
2, it returns
03:28 In the previous slide, you briefly learned about imperative programming, which is the opposite of functional programming. To conclude everything you just learned about, imperative programming changes the program’s state, and functional programming doesn’t.
Become a Member to join the conversation.