Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a value is a Keyword List

Tags:

elixir

Elixir provides a few is_ functions that let you check if an item is a specific type:

  • is_atom
  • is_binary
  • is_map
  • etc.

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?

like image 849
Sheharyar Avatar asked Oct 23 '16 21:10

Sheharyar


Video Answer


1 Answers

Turns out there is a built in solution; the Keyword module exports a keyword?/1 method:

Keyword.keyword?(term)

Returns true if term is a keyword list; otherwise returns false

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.

like image 152
Sheharyar Avatar answered Oct 22 '22 11:10

Sheharyar