Learn about functional programming in Python, pure functions, map(), filter(), zip(), reduce() concepts

Need for Functional Programming(FP)

  • The usage of Functional Programming provides us with separation of concern where we can separate data and logic separately. Hence, the code becomes clear and easy to understand to a developer.
  • Functional Programming follows the DRY (Do not Repeat Yourself) principle.
  • Code which follows Functional Programming practice is memory-efficient.
  • The codebase which implements Functional Programming will also be easy to extend and maintain.

Pure functions

  • One of the important concepts in functional programming is the usage of pure functions.
  • A function is said to be a Pure function if:
  1. Given the same input, the function will always return the same output.

  2. The function must not produce any side effects.

  • Side effects are things that a function does that affect the outside world, that is they change the state of the program.
  • Changing the data in a variable, printing output can be considered as some examples of side effects of a function.

Consider the following simple example:

Alt Text

The function square will always return only the square of a given number and will not change anything in the outside world. This type of functions are also called declarative functions

Note:

  • But, technically it’s not possible to use pure functions everywhere as we may need to change the state of the code.
  • Although, it’s a good practice to use pure functions as many places as possible.
  • And the fact here is that it highly probable to face bugs and errors occur in non-pure functions rather than in pure functions.
  • Python provides us with some useful pure functions which are built-in python.

Pure Functions in python:

  1. map()
  2. filter()
  3. zip()
  4. reduce()

#python #web-development #programming #developer #machine-learning

Functional Programming in Python For Beginners
2.15 GEEK