When running
1..10000000000000000000 |> Enum.sum
The result is computed in what seems like constant time - I assume it uses the formula 1+ 2+ ... + n = n(n+1) / 2
What allows elixir to make this optimization? is the 1..n notation different than declaring a normal list as [1,2,3]
. When I inspect 1..100000
it appears to return a string. What's going on here?
1..10000000000000000000
is a Range
and Elixir has a special case in Enum.sum
for ranges which uses the integer summation formula:
def sum(first..last) when last > first do
div((last + first) * (last - first + 1), 2)
end
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With