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

ls.reduceLeft(_ max _) // is equivalent to ls.max

Same can be accomplished via foldLeft or foldRight.

ls.foldLeft(Int.MaxValue) (_ min _)

ls.foldLeft(Int.MinValue) (_ max _)

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))
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s