Related Tags

elixir

# What is a pure function?

Mohe Ud Din Sheikh

## Introduction

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.

### Example

iex> sum = &(&1 + &2 + &3)

iex> sum.(10, 3 , 5)
#Output = 18

iex> sum.(14, 2 , 1)
#Output = 17

iex> sum.(2, 1 , 5)
#Output = 8

iex> sum.(10, None , 5)
#Output = Error
iex> sum.(None, 3 , 5)
#Output = Error

The pure function

You can try using the function in the terminal below :

Terminal 1
Terminal

### Explanation

• Line 1: We create a function that calculates the sum of all three parameters’ values.

• Line 3–15: We call the sum function and try it with different parameter values.

RELATED TAGS

elixir

CONTRIBUTOR

Mohe Ud Din Sheikh
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time