Skip to content

Optimize Enum.to_list for ranges, closes #12383 #12384

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/elixir/lib/enum.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3675,6 +3675,7 @@ defmodule Enum do
"""
@spec to_list(t) :: [element]
def to_list(enumerable) when is_list(enumerable), do: enumerable
def to_list(%{__struct__: Range} = range), do: Range.to_list(range)
def to_list(%_{} = enumerable), do: reverse(enumerable) |> :lists.reverse()
def to_list(%{} = enumerable), do: Map.to_list(enumerable)
def to_list(enumerable), do: reverse(enumerable) |> :lists.reverse()
Expand Down
20 changes: 20 additions & 0 deletions lib/elixir/lib/range.ex
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,26 @@ defmodule Range do
end
end

@doc """
Converts a range to a list.
"""
@doc since: "1.15.0"
def to_list(first..last//step)
when step > 0 and first <= last
when step < 0 and first >= last do
:lists.seq(first, last, step)
end

def to_list(_first.._last//_step) do
[]
end

# TODO: Remove me on v2.0
def to_list(%{__struct__: Range, first: first, last: last}) do
step = if first <= last, do: 1, else: -1
:lists.seq(first, last, step)
end

@doc """
Checks if two ranges are disjoint.

Expand Down