English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
[Caml-list] User-defined equality on types?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2001-04-23 (11:57)
From: John R Harrison <johnh@i...>
Subject: Re: [Caml-list] User-defined equality on types?

Hi Francisco,

| Have you considered using functors defining your datatype
| structures? In that way you can customise the use of equality
| throught the whole module with something like:
| [...]

Thanks for the suggestion; I hadn't considered using functors. But I'm
not quite sure I understand your idea completely. I see how I can
localize the instances of the custom equality operation, but it seems
I still need to make explicit reference to a non-standard equality
*outside* the module, and it doesn't happen "transparently", still
less in composite data structures. This is the critical thing that I
want. For example, suppose I have a type of integers modulo 2 with a
non-canonical representation and a user-defined equality relation:

  module Mod2 =
      type z2 = Integer of int
      let (=) (Integer m) (Integer n) = (m - n) mod 2 = 0
      let mk n = Integer n
      let dest(Integer n) = n mod 2

I want all equality on type "z2" to use this defined equality
relation, including on the appropriate fields of composite data
structures where some but (maybe not all) components are of type
"z2". But this doesn't happen by default:

  # let x = Mod2.mk 3 and y = Mod2.mk 5;;
  val x : Mod2.z2 = Mod2.Integer 3
  val y : Mod2.z2 = Mod2.Integer 5
  # x = y;;
  - : bool = false

If I explicitly refer to Mod2.(=), then all is well:

  # Mod2.(=) x y;;
  - : bool = true

But this doesn't happen automatically on composite data structures:

  # (x,1) = (y,1);;
  - : bool = false

and if I open the module, the regular equality is hidden:

  # open Mod2;;
  # x = y;;
  - : bool = true
  # (x,1) = (x,2);;
  This expression has type Mod2.z2 * int but is here used with type Mod2.z2

Can I use your idea to set things up to do what I want?

Btw, Alain Frisch's message reminded me that one would also like to be
able to customize the generic hashing function to ensure it's substitutive
w.r.t. the defined equality relation.

Of course, the "z2" example is articifial. But there are lots of real
situations where one might want types to be represented
non-canonically. For example, I think the standard library's sets,
represented by quasi-balanced trees, are non-canonical.

To unsubscribe, mail caml-list-request@inria.fr.  Archives: http://caml.inria.fr