Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

equality combinators for variant types #197

Closed
nilsbecker opened this issue Feb 19, 2018 · 4 comments
Closed

equality combinators for variant types #197

nilsbecker opened this issue Feb 19, 2018 · 4 comments

Comments

@nilsbecker
Copy link
Contributor

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?

@nilsbecker
Copy link
Contributor Author

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?

@c-cube
Copy link
Owner

c-cube commented Feb 19, 2018

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 :)

@c-cube c-cube closed this as completed Feb 19, 2018
@nilsbecker
Copy link
Contributor Author

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

@madroach
Copy link

madroach commented Oct 6, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants