Pure vs. Impure Functions
Learn to distinguish pure functions that return consistent results from impure functions that produce side effects or unpredictable outputs. Explore practical Elixir examples and understand strategies to isolate impure functions, enabling you to write more predictable and maintainable functional code.
We'll cover the following...
When we can’t predict the results of a function, the function is impure. But before we can devise a strategy to handle impure functions, we need to know how to identify them. In this lesson, we’ll learn all the differences between predictable pure functions and unpredictable impure functions. In this course, we’ve seen many examples that contain impure and pure functions, but we didn’t stop to understand their properties. Now, we’ll explore them and understand how to identify them by writing some examples.
Pure functions are predictable
Pure functions always return consistent output when given the same input and never produce effects beyond the function’s scope, making them predictable. For example, write the following function that calculates the total from a given price and tax value:
iex> total = &(&1 * &2/100)
iex> total.(100, 8)
#Output -> 8.0
iex> total.(100, 8)
#Output -> 8.0
iex> total.(nil, 8)
#Output -> ** (ArithmeticError)
iex> total.(nil, 8)
#Output -> ** (ArithmeticError)
Try it below:
With a pure function, we can try total.(100, 8) a thousand times. We’ll always see the same result. If we try calculate_tax.(nil, 8), it always generates an error. Pure functions can result in errors, but the errors are predictable.
Pure functions are very ...