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
source share