Skip to content

Commit db7c28f

Browse files
sabiwarajosevalim
authored andcommitted
Fix bug in Enum.slice with step>1 (#12042)
1 parent f581049 commit db7c28f

File tree

2 files changed

+10
-21
lines changed

2 files changed

+10
-21
lines changed

lib/elixir/lib/enum.ex

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4469,29 +4469,15 @@ defmodule Enum do
44694469

44704470
{:error, module} ->
44714471
{list, count} =
4472-
if step == 1 do
4473-
enumerable
4474-
|> module.reduce({:cont, {[], 0}}, fn elem, {acc, count} ->
4475-
{:cont, {[elem | acc], count + 1}}
4476-
end)
4477-
|> elem(1)
4478-
else
4479-
# We want to count all elements but we only keep the ones we need
4480-
{_, {list, _, count}} =
4481-
module.reduce(enumerable, {:cont, {[], 1, 0}}, fn
4482-
elem, {acc, 1, count} ->
4483-
{:cont, {[elem | acc], step, count + 1}}
4484-
4485-
_elem, {acc, to_drop, count} ->
4486-
{:cont, {acc, to_drop - 1, count + 1}}
4487-
end)
4488-
4489-
{list, count}
4490-
end
4472+
enumerable
4473+
|> module.reduce({:cont, {[], 0}}, fn elem, {acc, count} ->
4474+
{:cont, {[elem | acc], count + 1}}
4475+
end)
4476+
|> elem(1)
44914477

44924478
{count,
4493-
fn start, amount, _step ->
4494-
list |> :lists.reverse() |> slice_exact(start, amount, 1, count)
4479+
fn start, amount, step ->
4480+
list |> :lists.reverse() |> slice_exact(start, amount, step, count)
44954481
end}
44964482
end
44974483
end

lib/elixir/test/elixir/enum_test.exs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1094,6 +1094,9 @@ defmodule EnumTest do
10941094

10951095
assert [1, 2, 3] |> Stream.cycle() |> Stream.take(10) |> Enum.slice(-10..-6//2) ==
10961096
[1, 3, 2]
1097+
1098+
assert [1, 2, 3] |> Stream.cycle() |> Stream.take(10) |> Enum.slice(-9..-5//2) ==
1099+
[2, 1, 3]
10971100
end
10981101

10991102
test "sort/1" do

0 commit comments

Comments
 (0)