Skip to content

Instantly share code, notes, and snippets.

@simonewebdesign
Created August 22, 2016 16:01
Show Gist options
  • Save simonewebdesign/39aa3f82634b146ee0b6ee810ec86a58 to your computer and use it in GitHub Desktop.
Save simonewebdesign/39aa3f82634b146ee0b6ee810ec86a58 to your computer and use it in GitHub Desktop.
@doc """
Returns the sum of all elements.
Raises `ArithmeticError` if `enumerable` contains a non-numeric value.
## Examples
iex> Enum.sum([1, 2, 3])
6
"""
@spec sum(t) :: number
def sum(enumerable)
def sum(first..first),
do: first
def sum(first..last) when last < first,
do: sum(last..first)
def sum(first..last) when last > first do
div((last + first) * (last - first + 1), 2)
end
def sum(enumerable) do
reduce(enumerable, 0, &+/2)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment