Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pure function
elixir
communitycreator

What is a pure function in Elixir?

Muaz Ali

Introduction

A pure function is an essential part of functional programming. Let's explore what a pure function means.

Pure functions

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.

Example

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)
A pure function that prints the Fibonacci sequence

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.

Impure functions

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
An impure function that prints a certain 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.

RELATED TAGS

pure function
elixir
communitycreator

CONTRIBUTOR

Muaz Ali
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring