You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Immutability and pure functions are two foundational principles of functional programming. Together, they eliminate many common sources of bugs and make programs easier to reason about, test, and parallelise.
A pure function has two properties:
-- Pure: always returns the same result for the same input
add :: Int -> Int -> Int
add x y = x + y
-- Pure: no side effects
square :: Int -> Int
square x = x * x
# Pure
def add(x, y):
return x + y
# Pure
def square(x):
return x * x
# Impure: modifies external state (side effect)
counter = 0
def increment():
global counter
counter += 1
return counter
# Impure: depends on external state (not deterministic)
import random
def random_number():
return random.randint(1, 10)
# Impure: performs I/O (side effect)
def greet(name):
print(f"Hello, {name}!")
return name
# Impure: modifies input (side effect)
def add_item(lst, item):
lst.append(item) # Mutates the original list
return lst
| Property | Pure Function | Impure Function |
|---|---|---|
| Same inputs → same output | Always | Not necessarily |
| Modifies external state | Never | May do so |
| Performs I/O | Never | May do so |
| Easy to test | Yes | Depends on context |
| Safe for parallel execution | Yes | Requires synchronisation |
An expression is referentially transparent if it can be replaced with its value without changing the program's behaviour.
-- x is referentially transparent
x = add 3 4 -- x = 7
-- Anywhere we see 'add 3 4', we can substitute 7
result = x + x -- Same as 7 + 7 = 14
Pure functions are always referentially transparent. This makes functional programs easier to reason about and optimise — the compiler can freely rearrange or cache results.
Immutability means that once a value is created, it cannot be changed. Instead of modifying data in place, you create new data structures with the desired changes.
# Mutable list
numbers = [1, 2, 3]
numbers.append(4) # Modifies the original list
numbers[0] = 10 # Modifies the original list
# numbers = [10, 2, 3, 4]
# Creating new lists instead of modifying
numbers = (1, 2, 3) # Tuple — immutable
new_numbers = numbers + (4,) # Creates a new tuple
# numbers is still (1, 2, 3)
# new_numbers is (1, 2, 3, 4)
In Haskell, all values are immutable. There are no assignment statements that change a variable's value.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.