You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
In functional programming, recursion replaces loops as the primary mechanism for repetition. Since FP discourages mutable state (no loop counters that change), recursive functions call themselves with modified arguments until a base case is reached.
Recursion occurs when a function calls itself. Every recursive function needs:
The factorial of n (written n!) is:
Haskell:
factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial (n - 1)
factorial 5 -- 5 * 4 * 3 * 2 * 1 * 1 = 120
Python:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
factorial(5) # 120
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.