c-cube/ocaml-containers

equality combinators for variant types

nilsbecker opened this issue · 4 comments

what's the best way to make equality functions for variant types? can there be a general combinator that says: all variants are unequal but within one variant, equality is decided by the argument of the constructor, with an inner equality function?

i suspect this cannot be solved generally for unknown variant types. practically, what is the best way to provide an equality in the absence of polymorphic compare? write it all out with matching by hand?

Yes, the clean way is to write it by hand (or use ppx_deriving.eq to do it for you). It's also fine to let equal : t -> t -> bool = Pervasives.(=) in a module, as long as you know that the polymorphic operator coincides with the semantic equality. Outside of the module you use Foo.equal.

I don't think you can have a generic combinators. For non recursive types you might do this if most cases are trivial:

type t = A of int * bool | B | C | …

let equal x y : bool = match x, y with
  | A (i,_), A(j, _) -> CCInt.equal i j
  | A _, _ | _, A _ -> false
  | _ -> Pervasives.(=) x y

edit: please re-open if the answer is not satisfying :)

ok, thanks. good point to keep in mind that it's ok to use the polymorphic compare when the use case is unproblematic!

Hi,
I used to restore comparison operators in containers by always doing

open Containers
open Pervasives

This stopped working since Pervasives has been superseded by Stdlib, which includes all Modules and will in turn override the modules in Container when opened.
It would be helpful if you could ship an alternative main Container module or at least something like Polycompare to be opened after Container.