Skip to content
Open
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
14 changes: 12 additions & 2 deletions lib/elixir/lib/kernel.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4128,6 +4128,9 @@ defmodule Kernel do
and right lists don't match, destructuring simply stops
instead of raising an error.

An explicit tail in the left-hand list, such as `[head | tail]`, raises
an `ArgumentError` at compile time.

## Examples

iex> destructure([x, y, z], [1, 2, 3, 4, 5])
Expand All @@ -4142,8 +4145,7 @@ defmodule Kernel do
iex> {x, y, z}
{1, nil, nil}

The left-hand side supports any expression you would use
on the left-hand side of a match:
Each element of the left-hand list can be any pattern:

iex> x = 1
iex> destructure([^x, y, z], [1, 2, 3])
Expand All @@ -4155,6 +4157,14 @@ defmodule Kernel do
do).
"""
defmacro destructure(left, right) when is_list(left) do
case :lists.reverse(left) do
[{:|, _, [_, _]} | _] ->
raise ArgumentError, "destructure/2 does not support a tail in the left-hand list"

_ ->
:ok
end

quote do
unquote(left) = Kernel.Utils.destructure(unquote(right), unquote(length(left)))
end
Expand Down
8 changes: 8 additions & 0 deletions lib/elixir/test/elixir/kernel_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1238,6 +1238,14 @@ defmodule KernelTest do
end

describe "destructure" do
test "rejects a top-level cons pattern" do
assert_raise ArgumentError,
"destructure/2 does not support a tail in the left-hand list",
fn ->
Macro.expand_once(quote(do: destructure([a, b | tail], [1, 2, 3])), __ENV__)
end
end

test "less args" do
destructure [x, y, z], [1, 2, 3, 4, 5]
assert x == 1
Expand Down