Elixir provides a few is_
functions that let you check if an item is a specific type:
is_atom
is_binary
is_map
But how do I check if a value is a Keyword List in Elixir? I understand that underneath, Keyword Lists are a list of 2-element tuples with the first element as an atom, so my current workaround is this:
defmodule KList do
def is_keyword?(list) when is_list(list) do
Enum.all? list, fn item ->
case item do
{k, _} -> is_atom(k)
_ -> false
end
end
end
def is_keyword?(_), do: false
end
Is there a better (or an in-built) way of doing this? And more importantly, how can I do this in a when
clause?
Turns out there is a built in solution; the Keyword
module exports a keyword?/1
method:
Keyword.keyword?(term)
Returns
true
ifterm
is a keyword list; otherwise returnsfalse
Example:
iex> Keyword.keyword?([])
true
iex> Keyword.keyword?([a: 1]
true
iex> Keyword.keyword?([{Foo, 1}])
true
iex> Keyword.keyword?([{}])
false
iex> Keyword.keyword?([:key])
false
iex> Keyword.keyword?(%{})
false
Note: Unlike other is_
exports in the Kernel, keyword?
is not a macro – that means it cannot be used in guards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With