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
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.