Min/max with Option[T] for possibly empty Seq?

ScalaScala Collections

Scala Problem Overview


I'm doing a bit of Scala gymnastics where I have Seq[T] in which I try to find the "smallest" element. This is what I do right now:

val leastOrNone = seq.reduceOption { (best, current) =>
	if (current.something < best.something) current
	else best
}

It works fine, but I'm not quite satisfied - it's a bit long for such a simple thing, and I don't care much for "if"s. Using minBy would be much more elegant:

val least = seq.minBy(_.something)

... but min and minBy throw exceptions when the sequence is empty. Is there an idiomatic, more elegant way of finding the smallest element of a possibly empty list as an Option?

Scala Solutions


Solution 1 - Scala

seq.reduceOption(_ min _)

does what you want?


Edit: Here's an example incorporating your _.something:

case class Foo(a: Int, b: Int)
val seq = Seq(Foo(1,1),Foo(2,0),Foo(0,3))
val ord = Ordering.by((_: Foo).b)
seq.reduceOption(ord.min)  //Option[Foo] = Some(Foo(2,0))

or, as generic method:

def minOptionBy[A, B: Ordering](seq: Seq[A])(f: A => B) = 
  seq reduceOption Ordering.by(f).min

which you could invoke with minOptionBy(seq)(_.something)

Solution 2 - Scala

Starting Scala 2.13, minByOption/maxByOption is now part of the standard library and returns None if the sequence is empty:

seq.minByOption(_.something)

List((3, 'a'), (1, 'b'), (5, 'c')).minByOption(_._1) // Option[(Int, Char)] = Some((1,b))
List[(Int, Char)]().minByOption(_._1)                // Option[(Int, Char)] = None

Solution 3 - Scala

A safe, compact and O(n) version with Scalaz:

xs.nonEmpty option xs.minBy(_.foo)

Solution 4 - Scala

Hardly an option for any larger list due to O(nlogn) complexity:

seq.sortBy(_.something).headOption

Solution 5 - Scala

Also, it is available to do like that

Some(seq).filter(_.nonEmpty).map(_.minBy(_.something))

Solution 6 - Scala

How about this?

import util.control.Exception._
allCatch opt seq.minBy(_.something)

Or, more verbose, if you don't want to swallow other exceptions:

catching(classOf[UnsupportedOperationException]) opt seq.minBy(_.something)

Alternatively, you can pimp all collections with something like this:

import collection._

class TraversableOnceExt[CC, A](coll: CC, asTraversable: CC => TraversableOnce[A]) {

  def minOption(implicit cmp: Ordering[A]): Option[A] = {
    val trav = asTraversable(coll)
    if (trav.isEmpty) None
    else Some(trav.min)
  }

  def minOptionBy[B](f: A => B)(implicit cmp: Ordering[B]): Option[A] = {
    val trav = asTraversable(coll)
    if (trav.isEmpty) None
    else Some(trav.minBy(f))
  }
}

implicit def extendTraversable[A, C[A] <: TraversableOnce[A]](coll: C[A]): TraversableOnceExt[C[A], A] =
  new TraversableOnceExt[C[A], A](coll, identity)

implicit def extendStringTraversable(string: String): TraversableOnceExt[String, Char] =
  new TraversableOnceExt[String, Char](string, implicitly)

implicit def extendArrayTraversable[A](array: Array[A]): TraversableOnceExt[Array[A], A] =
  new TraversableOnceExt[Array[A], A](array, implicitly)

And then just write seq.minOptionBy(_.something).

Solution 7 - Scala

I have the same problem before, so I extends Ordered and implement the compare function. here is example:

 case class Point(longitude0: String, latitude0: String)  extends Ordered [Point]{

  def this(point: Point) = this(point.original_longitude,point.original_latitude)
  val original_longitude = longitude0
  val original_latitude = latitude0

  val longitude = parseDouble(longitude0).get 
  val latitude = parseDouble(latitude0).get  

  override def toString: String = "longitude: " +original_longitude +", latitude: "+ original_latitude

  def parseDouble(s: String):  Option[Double] = try { Some(s.toDouble) } catch { case _ => None }

  def distance(other: Point): Double =
    sqrt(pow(longitude - other.longitude, 2) + pow(latitude - other.latitude, 2))

 override def compare(that: Point): Int = {
  if (longitude < that.longitude)
    return -1
  else if (longitude == that.longitude && latitude < that.latitude)
    return -1
  else
    return 1
 }
}

so if I have a seq of Point I can ask for max or min method

  var points =  Seq[Point]()

val maxPoint = points.max
val minPoint = points.min

Solution 8 - Scala

You could always do something like:

case class Foo(num: Int)

val foos: Seq[Foo] = Seq(Foo(1), Foo(2), Foo(3))
val noFoos: Seq[Foo] = Seq.empty

def minByOpt(foos: Seq[Foo]): Option[Foo] =
  foos.foldLeft(None: Option[Foo]) { (acc, elem) => 
    Option((elem +: acc.toSeq).minBy(_.num)) 
  }

Then use like:

scala> minByOpt(foos)
res0: Option[Foo] = Some(Foo(1))

scala> minByOpt(noFoos)
res1: Option[Foo] = None

Solution 9 - Scala

For scala < 2.13

Try(seq.minBy(_.something)).toOption

For scala 2.13

seq.minByOption(_.something)

Solution 10 - Scala

In Haskell you'd wrap the minimumBy call as

least f x | Seq.null x = Nothing
          | otherwise  = Just (Seq.minimumBy f x) 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongustafcView Question on Stackoverflow
Solution 1 - ScalaLuigi PlingeView Answer on Stackoverflow
Solution 2 - ScalaXavier GuihotView Answer on Stackoverflow
Solution 3 - ScalaErik KaplunView Answer on Stackoverflow
Solution 4 - ScalaTomasz NurkiewiczView Answer on Stackoverflow
Solution 5 - ScalaAnar AmrastanovView Answer on Stackoverflow
Solution 6 - ScalaJean-Philippe PelletView Answer on Stackoverflow
Solution 7 - ScalaDvir AradView Answer on Stackoverflow
Solution 8 - Scalauser451151View Answer on Stackoverflow
Solution 9 - ScalaTanvir HassanView Answer on Stackoverflow
Solution 10 - ScalaDon StewartView Answer on Stackoverflow