Current section

Files

Jump to
journey lib factorial.ex
Raw

lib/factorial.ex

defmodule Factorial do
@moduledoc """
Computes the factorial of a non‑negative integer.
Returns :error for negative inputs.
"""
@spec factorial(integer) :: integer | :error
def factorial(n) when is_integer(n) and n >= 0 do
do_factorial(n, 1)
end
def factorial(_), do: :error
@spec do_factorial(integer, integer) :: integer
defp do_factorial(0, acc), do: acc
defp do_factorial(n, acc) when n > 0, do: do_factorial(n - 1, acc * n)
end