Convert boolean to integer in elixir

Is there a cleaner way to convert true → 1 and false → 0 than resorting to

if boolean_variable do 1 else 0 end 
+5
source share
2 answers

I am not aware of the built-in conversion function for this. How you build your own decision depends on what you want to achieve. Consider your implementation:

 def boolean_to_integer(bool) do if bool, do: 1, else: 0 end 

If you remember that all values ​​except nil and false are evaluated to true in the context of the conditional expression, this leads to the fact that

 iex> boolean_to_integer(0) 1 

If this is a problem, you can use the multi-clause function, which takes only boolean values:

 def boolean_to_integer(true), do: 1 def boolean_to_integer(false), do: 0 iex> boolean_to_integer(0) ** (FunctionClauseError) no function clause matching in MyModule.boolean_to_integer/1 iex:42: MyModule.boolean_to_integer(0) 

Of course, you can expand this to your liking, for example, to accept the integers 0 and 1 , and also nil you can do:

 def boolean_to_integer(true), do: 1 def boolean_to_integer(false), do: 0 def boolean_to_integer(nil), do: 0 def boolean_to_integer(1), do: 1 def boolean_to_integer(0), do: 0 iex> boolean_to_integer(0) 0 iex> boolean_to_integer(1) 1 
+8
source

You can shorten it using the following syntax, but since there is no explicit ternary operator in the language, an if macro is required.

if boolean_variable, do: 1, else: 0

Source: Elixir Short Description

+3
source

All Articles