Check if the value is a keyword list.

Elixir provides several is_ functions that let you check whether an element is of a particular type:

  • is_atom
  • is_binary
  • is_map
  • etc.

But how can I check if a value is a keyword list in Elixir? I understand that the keyword lists below are a list of two-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 built-in) way to do this? And more importantly, how can I do this in the when clause?

+10
source share
2 answers

It turns out there is a built-in solution; Keyword module exports keyword?/1 method:

Keyword.keyword? (Term)

Returns true if term is a list of keywords; 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 core, keyword? it is not a macro - it means that it cannot be used in protection.

+13
source

FTW macros!

 defmodule SomeMod do defmacro is_keywords(term) do quote do: Keyword.keyword?(unquote(term)) end def some_func(arg) when is_keywords(arg), do: "blah blah blah..." end 
0
source

Source: https://habr.com/ru/post/1258684/


All Articles