Created
August 22, 2016 16:01
-
-
Save simonewebdesign/39aa3f82634b146ee0b6ee810ec86a58 to your computer and use it in GitHub Desktop.
Implementation of sum in Elixir v1.3.2, taken from https://github.com/elixir-lang/elixir/blob/v1.3.2/lib/elixir/lib/enum.ex#L2096-L2122
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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