My question step by step:
1) I was implementing Brönnimann's small but cute minimax algorithms [1] in scala. So I ended up in something like this:
object Algo {
object detail {
class Iterator[A] (base: scala.Iterator[A]) { def minmax (less: (A,A) => Boolean): (A,A) = .... }
}
implicit def iter2AIter[A] (i: scala.Iterator[A]) = new detail.Iterator[A](i)
implicit def itbl2AIter[A] (i: scala.Iterator[A]) = new detail.Iterator[A](i.elements)
}
Note, that the ordering relation used in the minmax algorithm is defined by a function paramter of "minmax"
Fine, List(1,2,3) minmax(_ < _) compiles (and works) when Algo._ is imported.
2) Then I wanted to add a sensible default ordering which spells out the parameter "less".
I ended up with annother helper class
object Algo {
object detail {
....
class IteratorOverOrdered[A <: Ordered[A]] (i: scala.Iterator[A]) extends Iterator[A] (i) {
def minmax(): (A,A) = minmax(_ < _)
}
...
}
implicit def iter2AIteratorOverOrdered[A <: Ordered[A]] (i: scala.Iterator[A]) = new detail.IteratorOverOrdered[A](i)
implicit def itab2AIteratorOverOrdered[A <: Ordered[A]] (i: scala.Iterable[A]) = new detail.IteratorOverOrdered[A](i.elements)
This works also.
3) But neither a String nor an Int extend Ordered. So I found myself piling up helper classes and implicit conversions by
repeating 2) for more types.
4) So the question is: Is there a better way to express the following intent
"when class A has an operator "<" and "i" is an Iteraable[A], then "i.minmax" shall be a shorthand for "i.minmax(_ < _)
B:T:W: The basic scheme to implement an algorithm wher (e.g.) an ordering is defined by a
function parameter and give a sensible default by overloading is a common paractice in C++ and I find it natural.