Created
March 27, 2010 01:49
-
-
Save OlegIlyenko/345638 to your computer and use it in GitHub Desktop.
minBy and maxBy for Traversable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
println("Sorted: " + list.sortBy(_.balance)) | |
println("Max: " + list.maxBy(_.balance)) | |
println("Min: " + list.minBy(_.balance)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// implicits | |
class RichTraversable[T](t: Traversable[T]) { | |
def maxBy[B](fn: T => B)(implicit ord: Ordering[B]) = t.max(ord on fn) | |
def minBy[B](fn: T => B)(implicit ord: Ordering[B]) = t.min(ord on fn) | |
} | |
implicit def toRichTraversable[T](t: Traversable[T]) = new RichTraversable(t) | |
// example | |
case class Account(val balance: Int) | |
val list = List(Account(100), Account(250), Account(35), Account(410), Account(112)) | |
println("Sorted: " + list.sortBy(_.balance)) | |
println("Max: " + list.maxBy(_.balance)) | |
println("Min: " + list.minBy(_.balance)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment