billylanchantin

billylanchantin

Feedback for how `CompareChain` handles `nil`

nil is annoying for CompareChain and I would like it to be better. I’m looking for some feedback on approaches!

The problem

compare?/2 works quite well for reducing boilerplate when all the arguments are non-nil. But when nil is a possible value it leads to headaches.

At CargoSense, we currently have 4 separate comparison modules to deal with this problem:

  • DateTimeNilInfinity - nil > datetime and nil == nil
  • DateTimeNilNegInfinity - nil < datetime and nil == nil
  • DateTimeNilInfinityRaise - nil > datetime and nil raises if compared to nil
  • DateTimeNilNegInfinityRaise - nil < datetime and nil raises if compared to nil

It’s… ok. It deals with the problem in a succinct-ish way:

# Before
old && new && DateTime.compare(old, new) != :eq || old != new
# After
compare?(old != new, DateTimeNilInfinity)

The problem is that no one wants to read DateTimeNilNegInfinityRaise, let alone think though all the casework to understand what the code means.

I have considered a few options over the years. @benwilson512 recently advocated for another one but I remain undecided.

Options

1. SQL-like optional argument

We make CompareChain aware of nils and handle them specially.

compare?(old != new, DateTime, nils: :infinity)

nils can be one of: :infinity, :neg_infinity, :infinity_raise, :neg_infinity_raise. This is reminiscent of how SQL allows you to specify NULLS FIRST | LAST.

Downsides:

  • All nils would be necessarily be treated the same in a single expression.
  • All desired ways of handling nil would need to be represented as one of the options. (I.e. the 4 I listed may not be exhaustive.)

2. inf() and -inf()

(Courtesy of @benwilson512)

We provide expressions which CompareChain understands how to handle natively:

compare?(old || inf() != new || inf(), DateTime)
# or possibly
compare?(inf(old) != inf(new), DateTime)

Here we have -inf() < datetime < inf() (or whatever the struct is), inf() == inf(), and -inf() == -inf(). Then nil could be handled in the “normal” way of raiseing if passed to a function like DateTime.compare/2. And if you didn’t want that, you provide inline fallbacks.

Downsides:

  • Still a little verbose (and possibly hard to understand if we go with inf(old) != inf(new))

Other considerations

  • Current approach of defining bespoke modules automatically interopts with Enum.sort/2 and friends. The new approaches would not. (Though one could still define a bespoke module if one wanted.)

  • Certain 3-valued logics are simply impossible to encode using compare/2 #=> :lt | :eq | :gt. E.g. select 1 = null; in SQL returns null, meaning none of :lt | :eq | :gt are appropriate. We’ve sort of been handling this by raiseing internally. But just note that the design space for CompareChain is fundamentally limited in this regard since the intent is to interop with the existing compare/2 paradigm.


Feedback

Please LMK your thoughts! Given that CompareChain is so conceptually simple, I’m hesitant to add special casing. But nil really is annoying, so I’d love to hear any opinions.

Also please advocate for another approach you like if you think of one!

Most Liked

bruce

bruce

Author of Craft GraphQL APIs in Elixir with Absinthe

I’m a fan of the inf() approach for its flexibility.

Nit (naming): I think I’d use infinity(), personally. I think the keystrokes are worth the clarity, and I’ve seen :infinity used for case matching before. (:hot_pepper: : inf feels like an unwarranted homage to Python’s math.inf.)

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

To further advocate for this a bit I think it’s worth looking at how it handles more “normal” CompareChain scenarios since this != one is actually less common, and using the normal DateTime.compare? might actually be fine in this situation eg if new && old && DateTime.compare?(new, old) != :eq do

Consider:

if compare?(data.sync_cursor >= shadow.sync_cursor, DateTimeNilNegInfinity) do
  # stuff
end

What we are trying to deal with is that shadow.sync_cursor might be nil if the shadow is freshly initialized. In these cases we want nil to evaluate as less than any possible value of new_data.sync_cursor which is coming in. So in my proposal you’d have:

if compare?(data.sync_cursor >= shadow.sync_cursor || -inf(), DateTime) do
  # stuff
end

or

if compare?(data.sync_cursor >= -inf(shadow.sync_cursor), DateTime) do
  # stuff
end

to indicate that negative infinity is being used as a fallback for the value of shadow.sync_cursor.

This really improves the look I think of chained comparisons too:

compare?(si.activated_at <= geo_elem.latest_recorded_at <= si.deactivated_at || inf(), DateTime)

Because in this particular case we are being very explicit about which of the possible values we want to be OK with being nil.

Where Next?

Popular in Discussions Top

andre1sk
A big advantage to Elixir is all the distributed goodness but for many applications running on multiple nodes having integrated Etcd, Zoo...
New
arpan
Hello everyone :wave: Today I am very excited to announce a project that I have been working on for almost 3 months now. The project is...
New
chuck
Let me start by stating an assumption: Phoenix is a great approach to building REST APIs. There are many reasons for this, but I will ass...
New
nunobernardes99
Hi there Elixir friends :vulcan_salute: In a recent task I was on, I needed to check in two dates which of them is the maximum and which...
New
nburkley
AWS re:Invent is on at the moment with some interesting announcements. One new feature in particular is the Lambda Runtime API for AWS La...
New
ejpcmac
I have discovered Nix last month and I am currently on my way to migrating to it—both on macOS at home and the full NixOS distrubution at...
New
rower687
Hi all, I’ve been reading a lot about the “let it crash” term and how supervising processes and the whole messaging passing make an elixi...
New
acrolink
How does the two languages compare when it comes to server side application development? Any experiences or ideas? Thank you.
New
axelson
Decided against including more info in the title, but the gist is that Plataformatec sponsored projects will continue with the assets bei...
New
kostonstyle
Hi all How can I compare haskell with elixir, included tools, webservices, ect. Thanks
New

Other popular topics Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New

We're in Beta

About us Mission Statement