Skip to content

Raise ArgumentError in Keyword.keys when list is not a keyword list #10214

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
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
19 changes: 18 additions & 1 deletion lib/elixir/lib/keyword.ex
Original file line number Diff line number Diff line change
Expand Up @@ -431,13 +431,30 @@ defmodule Keyword do

iex> Keyword.keys(a: 1, b: 2)
[:a, :b]

iex> Keyword.keys(a: 1, b: 2, a: 3)
[:a, :b, :a]

iex> Keyword.keys([{:a, 1}, {"b", 2}, {:c, 3}])
** (ArgumentError) expected a keyword list, but an entry in the list is not a two-element tuple with an atom as its first element, got: {"b", 2}

"""
@spec keys(t) :: [key]
def keys(keywords) when is_list(keywords) do
:lists.map(fn {k, _} when is_atom(k) -> k end, keywords)
try do
:lists.map(
fn
{key, _} when is_atom(key) -> key
element -> throw(element)
end,
keywords
)
catch
element ->
raise ArgumentError,
"expected a keyword list, but an entry in the list is not a two-element tuple with an atom as its first element, " <>
"got: #{inspect(element)}"
end
end

@doc """
Expand Down