soc
soc

Reputation: 28433

How to define a max function for every type with a method ">"?

Is it possible to define it generically over all types which have a method > (also all AnyVals) so that using a single implementation method is enough?

Upvotes: 3

Views: 339

Answers (3)

oxbow_lakes
oxbow_lakes

Reputation: 134270

can you declare an implicit conversion:

implicit def greater2order[A](self : { def >(that : A) }) : Order[A] = ...

and then just use scalaz...

Upvotes: 4

huynhjl
huynhjl

Reputation: 41646

The standard library sort of does it already. But without assigning a type to the object having the > method...

List(1,2,3).max(Ordering.fromLessThan( (a:Int, b:Int) => b > a) )

Basically this syntax will work for anything that has a > method or where some implicit conversion makes > available. It creates an Ordering that can be passed to the standard max method.

One more example:

case class S(s:String) {
  def >(that:S) = java.text.Collator.getInstance.compare(s, that.s) > 0
}

List(S("abc"), S("ABa"), S("abd")).max(Ordering.fromLessThan( (a:S,b:S) => b>a) )
// res9: S = S(abd)

Upvotes: 3

user166390
user166390

Reputation:

The Ordering trait may be relevant.

It covers the standard numerical types (and then some -- see "Known Subclasses"). Implicits can be used to "open it up" across external types.

Happy coding.

Upvotes: 1

Related Questions