Scala Hacking: Computing min and max of a List
There are several ways to accomplish this. Next code snippet shows how to compute min and max using reduceLeft.
val ls = List(1,2,3,4,5)
ls.reduceLeft(_ min _) // is equivalent to ls.min
Same can be accomplished via foldLeft or foldRight.
ls.foldLeft(Int.MaxValue) (_ min _)
However, can we compute both min and max in one line? Check out the following snippet.
ls.map(
x=>(x,x)).reduceLeft(
(x,y) => (x._1 min y._1, x._2 max y._2)An alternative is to use foldLeft:
ls.foldLeft
((Int.MaxValue, Int.MinValue))
((acc:(Int,Int),y:Int) => (acc._1 min y, acc._2 max y))
Comments ()