diff --git a/lib/elixir/lib/calendar/date_range.ex b/lib/elixir/lib/calendar/date_range.ex index a92b9d124f5..5e8c652b781 100644 --- a/lib/elixir/lib/calendar/date_range.ex +++ b/lib/elixir/lib/calendar/date_range.ex @@ -95,7 +95,7 @@ defmodule Date.Range do [date_from_iso_days(current, calendar)] end - defp slice(current, step, remaining, calendar) do + defp slice(current, step, remaining, calendar) when remaining > 1 do [ date_from_iso_days(current, calendar) | slice(current + step, step, remaining - 1, calendar) diff --git a/lib/elixir/lib/enum.ex b/lib/elixir/lib/enum.ex index 33866871e1e..0bdff3f47f1 100644 --- a/lib/elixir/lib/enum.ex +++ b/lib/elixir/lib/enum.ex @@ -3674,9 +3674,14 @@ defmodule Enum do end def take(enumerable, amount) when is_integer(amount) and amount < 0 do - {count, fun} = slice_count_and_fun(enumerable, 1) - first = Kernel.max(amount + count, 0) - fun.(first, count - first, 1) + case slice_count_and_fun(enumerable, 1) do + {0, _fun} -> + [] + + {count, fun} -> + first = Kernel.max(amount + count, 0) + fun.(first, count - first, 1) + end end @doc """ @@ -5181,6 +5186,9 @@ defimpl Enumerable, for: Range do slice(Map.put(range, :step, step)) end - defp slice(_current, _step, 0), do: [] - defp slice(current, step, remaining), do: [current | slice(current + step, step, remaining - 1)] + defp slice(current, _step, 1), do: [current] + + defp slice(current, step, remaining) when remaining > 1 do + [current | slice(current + step, step, remaining - 1)] + end end diff --git a/lib/elixir/test/elixir/calendar/date_range_test.exs b/lib/elixir/test/elixir/calendar/date_range_test.exs index 39465421ca4..fe6cab37e59 100644 --- a/lib/elixir/test/elixir/calendar/date_range_test.exs +++ b/lib/elixir/test/elixir/calendar/date_range_test.exs @@ -101,6 +101,10 @@ defmodule Date.RangeTest do end end + test "Enum.take/1 for empty range with negative step" do + assert Enum.take(@empty_range, -1) == [] + end + test "works with date-like structs" do range = Date.range(~N[2000-01-01 09:00:00], ~U[2000-01-02 09:00:00Z]) assert range.first == ~D[2000-01-01]