Equality relations in Scala

前端 未结 3 1552
天命终不由人
天命终不由人 2021-01-05 03:01

I just stumbled on one of Tony Morris\' blog-posts about Java and a fundamental problem with the language: that of defining a bespoke equality-relation for a collection. Thi

相关标签:
3条回答
  • 2021-01-05 03:07

    You're describing the concept of a hashing strategy. The Trove library includes sets and maps that can be constructed with hashing strategies.

    0 讨论(0)
  • 2021-01-05 03:22

    I know you're asking about Scala, but it's worth comparing with what the .Net collections offer. In particular, all Hash-based collections (eg Dictionary<TKey, TValue> and HashSet<T>) can take an instance of IEqualityComparer<T>. This is similar to Scala's Equiv[T], but also supplies a custom hash code. You could create a similar trait by subclassing Equiv:

    trait HashEquiv[T] extends Equiv[T] {
      def hashOf(t: T) : Int
    }
    

    To be fully supported, hash based collections would need to add HashEquiv implicit parameters to their construction and use the implicitly imported equiv and hashOf methods instead of the Object instance methods (like TreeSet, etc do with the Ordered trait, but in reverse). There would also need to be an implicit conversion from Any to HashEquiv that uses the intrinsic equals and hashCode implementation.

    0 讨论(0)
  • 2021-01-05 03:23

    This can already be achieved with Java's TreeSet and a Comparator implementation:

    TreeSet<String> ignoreCase = new TreeSet<String>(new Comparator<String>(){
        @Override
        public int compare(String o1, String o2) {
            return o1.compareToIgnoreCase(o2);
        }});
    
    TreeSet<String> withCase = new TreeSet<String>();
    
    List<String> values = asList("A", "a");
    ignoreCase.addAll(values);
    withCase.addAll(values);
    

    Output:

    ignoreCase -> [A]
    withCase -> [A, a]
    

    This has the drawbacks that the Comparator to implement is more powerful than needed and that you're restricted to collections that support Comparators. As pointed out by oxbow_lakes the Comparator implementation breaks the Set contract (for !a.equals(b) it could be that new Set(); set.add(a) == true && set.add(b) == false).

    Scala supports this with a view transformation from A => Ordered[A].

    scala> new scala.collection.immutable.TreeSet[String]()(x=> x.toLowerCase) + "a"
     + "A"
    res0: scala.collection.immutable.TreeSet[String] = Set(A)
    
    0 讨论(0)
提交回复
热议问题