"Honey, I shrunk the function!"

Recursion is fun, and it makes code really clean and succinct. But what if we could make it even cleaner? We can, thanks to Coconut's Addpattern functionality.

Here's where we left off:

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

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

Using Addpattern, we can tell Coconut to basically do the recursion for us. Here's the syntax for that:

def factorial(0) = 1

@addpattern(factorial)
def factorial(n is int if n > 0) =
    """Compute n! where n is an integer >= 0."""
    range(1, n+1) |> reduce$(*)


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

Run the code to make sure the test cases pass!


Next
Previous