Search code examples
elixir

Convert boolean to integer in elixir


Is there any cleaner way to convert true -> 1 and false -> 0 than resorting to

if boolean_variable do
  1
else
  0
end

Solution

  • I am not aware of a built in conversion function for this. How you build your own solution 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 recall that all values except nil and false evaluate to true in the context of a conditional expression, this has the effect that

    iex> boolean_to_integer(0)
    1
    

    If this should be a problem, you can use a multi-clause function that only accepts booleans:

    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 extend this to your liking, for example to accept integers 0 and 1 as well as 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