I am trying to make a sequence (for example, other collection types are also conceivable) comparable to other sequences.
class RichSeq[A](val seq: Seq[A]) extends Ordered[RichSeq[A]]
Of course there is a implicit conversion in the refered package object:
implicit def seq2RichSeq[A](s: Seq[A]) = new RichSeq(s)
Comparing means, first size matters than each element. Code makes it clear:
class RichSeq[A](val seq: Seq[A]) extends Ordered[RichSeq[A]] {
def compare(s: RichSeq[A]) = {
seq.size compare s.seq.size match {
case 0 => seq.view.zip(s.seq).map { case (x,y) => ord.compare(x,y) }.dropWhile(_ == 0).headOption.getOrElse(0)
case x => x
}
}
}
But that doesn`t compile (of course) because one needs an ordering to compare the elements, so I tried that:
class RichSeq[A](val seq: Seq[A]) extends Ordered[RichSeq[A]] {
def compare(s: RichSeq[A])(implicit ord: Ordering[A]) = {
// ...
}
}
Now the signature of the compare method is not suitable, so I moved the implicit ord
to the class signature (and adapted the implicit conversion):
implicit def seq2RichSeq[A](s: Seq[A])(implicit ord: Ordering[A]) = new RichSeq(s)
class RichSeq[A](val seq: Seq[A])(implicit ord: Ordering[A]) extends Ordered[RichSeq[A]] {
def compare(s: RichSeq[A]) = {
// ...
}
}
But now I have a the problem, that all other methods in RichSeq
that I want to use via implicit
at a Seq[A]
also require an implicit Ordering[A]
and I can´t always deliver one. Sometimes I use my RichSeq
by methods without Ordering and sometimes the compare method.
For example, sometimes I call
def distinctBy[B](f: A => B): Seq[A] = {
seq.foldLeft { (Buffer[A](),MutMap[B,A]()) } {
case ((b,m),x) if m contains f(x) => (b,m)
case ((b,m),x) =>
m += f(x) -> x
b += x
(b,m)
}._1
}
meanwhile I am not able to define an Ordering[A]
.
I see one solution in having two different classes (with two implicit conversions):
class RichSeqOrderable[A](val seq: Seq[A])(implicit ord: Ordering[A]) extends Ordered[RichSeqOrderable[A]]
class RichSeq[A](val seq: Seq[A])
But I think that breaks the thought of having all stuff together?!?