Comparison chaining: Java vs Haskell
1 min read

Comparison chaining: Java vs Haskell

(20.09.12) For a much cleaner approach, see Tekmo’s comment on reddit.

For the first time in my life I’m hacking on corporate Java code and, well, ever so occasionally it can be frustrating. The Google Guava libraries make Java programming more bearable by introducing common helper functions, immutable data structures and a few more gadgets, but their lack of orthogonality leaks out whenever what you need is not in the library.

A common scenario in Java is making a comparison function for a class that has a couple of comparable constituents. You impose some sort of lexicographic order and compare using nested assignments, nested if else statements or the trinary operator. In this example, lets say we are in a function, so we can leverage return. It’s still pretty verbose.

Guava introduces a ComparisonChain class, that enables a declarative approach.

Can we repeat this in Haskell? There is a nice and short solution exploiting that Ordering is a Monoid instance.

However, there is a problem with this approach. Lists are homogenous in Haskell, so we would not be able to compare elements of different types within one lexicographic comparison. Instead, we can create a micro DSL using the Either monad. It’s useful because Left, normally used for exceptions, can “exit” a do statement, which is exactly what we need when we get a non equal comparison any time in the chain.

Source code.

Much better.