A pure function is an essential part of functional programming. Let's explore what a pure function means.
A pure function is a method or function in functional programming that does not affect the state of the program. This means that a pure function cannot be used to mutate or change variables or objects declared in the program. A pure function also does not interact with the I/O. Its output is also deterministic, whereas an impure function does not have a deterministic output.
In the context of Elixir, the following code is an example of a pure function:
defmodule Math do def fibonacci(0) do 0 end def fibonacci(1) do 1 end def fibonacci(n) do fibonacci(n-1) + fibonacci(n-2) end end IO.puts Math.fibonacci(9)
In the above function, a state variable or object isn't affected and I/O is not used. The above function also does not rely on a variable to perform its operations and all of its processing is done locally without changing any state in the program. It is deterministic also, which means that given any input to this function, it will always return the same value specific to that input.
To understand an impure function, We'll contrast it with the pure functions. Let's look at the following example:
defmodule Name do def print_name() do name = "Elon" IO.puts name end end Name.print_name
The above code's output is not deterministic. We cannot predict what any user will input. This characteristic makes it impure. Furthermore, this function's invocation of I/O calls also makes it impure because I/O operations interact and modify the state of the program.
View all Courses