Home Menu
Pipelines Pattern Matching
Learning Pattern Matching Pattern Matching Example
Add Pattern Recursion Data Types
Syntax Binary Trees
Iterators
First exposure Iterator chaining Iterator slicing Lazy Evaluation
Lazy Lists
In Python In Coconut
Recursive Factorial
Base Case Recursive Call Error Handling Wildcard Pattern Automatic Tail Call Optimization

Recursive Call

Next, we’ll add the recursive call. Here's where we left off:

def factorial(n):
    """Compute n! where n is an integer >= 0."""
    case n:
        match 0:
            return 1

# Test cases:
0 |> factorial |> print  # 1
3 |> factorial |> print  # 6

We want our next match statement to check if n is an integer and greater than 0.

Add a match statement that checks whether n matches to x is int. This'll check if n is an integer.

The second attribute of n we want to check for is if it’s greater than 0. To do this, add the conditional if x > 0 right after the x is int pattern.

If n matches this pattern, we want to return n times the recursive call to factorial.

Double-click starter code, implement the recursive call, and then run the code to make sure the test cases pass!

Show Solution:


Next
Previous

Coconut Editor

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX