Option for enforcing type check while doing comparison

31 views
Skip to first unread message

miwee

unread,
Oct 12, 2017, 9:05:57 PM10/12/17
to elixir-lang-core
consider following code segment

  def valid_row?(%{"acu" => acu}) when is_number(acu) do
    acu_limit = Application.get_env(:beam_checker, :acu_limit)
    acu > acu_limit
  end

since elixir/erlang comparison operator is very broad, the above code will never throw any exception irrespective of what is the data type or value for acu and acu_limit. But the end result is totally unexpected in cases where wrong types are supplied. two actual error cases which happened (and took some time to discover due to no exception) :
1) acu_limit was not defined in config, hence acu_limit got value nil
2) acu_limit was defined as string value in config

possible options for discussion:
1) can we have Integer.compare and Float.compare functions. That way whenever numeric comparisons are needed, these dedicated functions can be used. (preferred)
2) strict comparison version of > and < operators (something along the lines of == and ===, but for comparison)

option not for discussion
1) make a private comparison function, which throws an error if input values are not numbers. this is what I currently did.

thanks
miwee 

OvermindDL1

unread,
Oct 13, 2017, 10:15:28 AM10/13/17
to elixir-lang-core
This is something I've wanted for a long time.  If we have a `compare` function on all the main type modules like String, Atom, Binary, Integer, Float, etc... then we'd be able to pass in the module atom as a witness through functions along with the value type, it is one of the best ways you can do type based programming in a purely dynamic language.
.
Reply all
Reply to author
Forward
0 new messages