Coconut-enabled Improvements: Wildcard Pattern

Now we have a functional factorial implementation:

def factorial(n):
    """Compute n! where n is an integer >= 0."""
    case n:
        match 0:
            return 1
        match x is int if x > 0:
            return x * factorial(x-1)
    else:
        raise TypeError("the argument to factorial must be an integer >= 0")

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

One easy improvement we can make to our factorial function is to make use of the wildcard pattern, _. We don't actually need to assign x as a new variable, since it has the same value as n, so if we use _ instead of x, Coconut won't ever actually assign the variable. Thus, we can rewrite our factorial function without using x.

Replace the first occurrence of x with the wildcard pattern, _, and all the other occurrences of x with n.

Run the code to make sure the test cases pass!

Show Solution:


Next
Previous