Function to covert arbitrary data to boolean?

In python we have function bool() that converts to boolean everything, with the same rules as “if” does.
Do we have something similar in Elixir? I.e. for nil and false it will return false, and true for everything else

2 Likes

There is the convention to double bang:

iex> !!nil
false
iex> !!1
true
10 Likes

Thank you, it’s exactly that i needed

1 Like

be aware that

python:

>>> bool([])
False
>>> bool(0)
False
>>> bool(None)
False
>>> bool("")
False
>>> bool(set())
False
>>> bool({})
False
>>> bool(tuple())
False

Elixir:

iex(1)> !![]
true
iex(2)> !!0
true
iex(3)> !!nil
false
iex(4)> !!""
true
iex(5)> !!MapSet.new()
true
iex(6)> !!%{}
true
iex(7)> !!{}
true
1 Like

(deleted because I’m not interested in flame wars about type safety and the like)

I cannot think of an occasion when I want to check the term for being empty and at the same time I have no idea if it’s a list, a map, or a binary.

Such functions are a rails-like cancer and should be avoided at any cost.

2 Likes