View Source CompareChain (compare_chain v0.4.0)
Convenience macros for doing comparisons
Link to this section Summary
Functions
Macro that performs chained comparison using operators like <
and
combinations using and
or
, and not
.
Similar to compare?/1
except you can provide a module that defines a
compare/2
for semantic comparisons.
Link to this section Functions
Macro that performs chained comparison using operators like <
and
combinations using and
or
, and not
.
examples
Examples
Chained comparison:
iex> import CompareChain
iex> compare?(1 < 2 < 3)
true
Comparisons joined by logical operators:
iex> import CompareChain
iex> compare?(1 >= 2 >= 3 or 4 >= 5 >= 6)
false
notes
Notes
You must include at least one comparison like <
in your expression.
Failing to do so will result in a compile time error.
Including a struct in the expression will result in a warning.
You probably want to use compare?/2
instead.
Similar to compare?/1
except you can provide a module that defines a
compare/2
for semantic comparisons.
This is like how you can provide a module as the second argument to
Enum.sort/2
.
examples
Examples
Basic comparison (note how a < b == false
natively because of structural
comparison):
iex> import CompareChain
iex> a = ~D[2017-03-31]
iex> b = ~D[2017-04-01]
iex> a < b
false
iex> compare?(a < b, Date)
true
Chained comparison:
iex> import CompareChain
iex> a = ~D[2017-03-31]
iex> b = ~D[2017-04-01]
iex> c = ~D[2017-04-02]
iex> compare?(a < b < c, Date)
true
Comparisons joined by logical operators:
iex> import CompareChain
iex> a = ~T[15:00:00]
iex> b = ~T[16:00:00]
iex> c = ~T[17:00:00]
iex> compare?(a < b and b > c, Time)
false
More complex expressions:
iex> import CompareChain
iex> compare?(%{a: ~T[16:00:00]}.a <= ~T[17:00:00], Time)
true
Custom module:
iex> import CompareChain
iex> defmodule AlwaysGreaterThan do
iex> def compare(_left, _right), do: :gt
iex> end
iex> compare?(1 > 2 > 3, AlwaysGreaterThan)
true
notes
Notes
You must include at least one comparison like <
in your expression.
Failing to do so will result in a compile time error.