hnhl
hnhl

Reputation: 137

check if list contains atom key and has a value

How do I check if a key value pair exists in a List?

options = [symbol: ?|]

args = options[:symbol]

if args[:symbol] and not is_integer(args[:symbol]) do
...

This gives me the error (BadBooleanError) expected a boolean on left-side of "and", got: 124

Upvotes: 0

Views: 1178

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

There is a subtle difference between and/2 and &&/2 (the same applies to or/2 and ||/2.) The former operates on boolean values, the latter on truthy and falsey.

So one might change the code to

if args[:symbol] && not is_integer(args[:symbol]), do: ...

But this code is still not correct (at least it smells.) Keywords might have nils as values, so one must clearly distinguish between has nil value and does not have a value.

For that we have Keyword.has_key?/2. That said, the correct code would be:

if Keyword.has_key?(args, :symbol) and not is_integer(args[:symbol]), do: ...

Note and/2 here; it’s now correct because Keyword.has_key/2 does indeed return a boolean.

Upvotes: 2

Related Questions