Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Elixir's Enum.sum so fast?

Tags:

elixir

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?

like image 466
Scientaster Avatar asked Dec 07 '22 19:12

Scientaster


1 Answers

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

like image 198
Dogbert Avatar answered Dec 20 '22 21:12

Dogbert