Why is Elixir Enum.sum so fast?

At startup

1..10000000000000000000 |> Enum.sum

The result is calculated as constant time - I assume that it uses the formula 1+ 2+ ... + n = n(n+1) / 2

What allows the elixir to do this optimization? is a 1..n symbol other than the declaration of a regular list as [1,2,3]. When I check 1..100000, it returns a string. What's going on here?

+4
source share
1 answer

1..10000000000000000000is Range, and Elixir has a special case in Enum.sumfor ranges in which an integer summation formula is used:

def sum(first..last) when last > first do
  div((last + first) * (last - first + 1), 2)
end

Source

+13
source

Source: https://habr.com/ru/post/1668977/


All Articles