Minimum Integer List value, if it can be empty in scala

I am trying to find the minimum value of an integer list and when it can be empty.

scala> val minValue:Int = List() match {
     |   case Nil => -1
     |   case xs  => xs.min
     | }
<console>:9: error: diverging implicit expansion for type Ordering[B]
starting with method Tuple9 in object Ordering
     case xs => xs.min

although it worked well not on an empty list.

scala> val minValue = List(1,2) match {
     |   case Nil => -1
     |   case xs  => xs.min
     | }
minValue: Int = 1

How to find min with sorting, since one of the ways I could think of is to sort and get the head with getOrElse defaultValue.

+3
source share
3 answers

The problem is that typechecker does not know which type to use for List(). If you specifically annotate an empty list with a type, it should work fine:

val minValue:Int = List.empty[Int] match { // ...

@senia , , , -1 "", " ", . , Option Scala , Some None . Scala :

scala> List.empty[Int].reduceLeftOption(_ min _)
res0: Option[Int] = None

scala> List(5, 2, 1, 3, 4).reduceLeftOption(_ min _)
res1: Option[Int] = Some(1)
+3

, : List[Nothing] List[Int], :

List[Int]() match {
  case Nil => -1;
  case xs => xs.min;
}

// -1

:

import scala.collection.GenTraversableOnce

implicit class MinMaxOpt[T](val l: GenTraversableOnce[T]) extends AnyVal {
  def minOpt(implicit o: Ordering[T]) = if (l.isEmpty) None else Some(l.min)
  def minOrElse[T2 >: T](default: T2)(implicit o: Ordering[T]) = minOpt getOrElse default

  def maxOpt(implicit o: Ordering[T]) = if (l.isEmpty) None else Some(l.max)
  def maxOrElse[T2 >: T](default: T2)(implicit o: Ordering[T]) = maxOpt getOrElse default
}

List(1, 2).minOpt
// Some(1)

List[Int]().minOrElse(-1)
// -1
+1

. List.min ScalaDoc.

def min[B >: A](implicit cmp: Ordering[B]): A

, List() , List[Nothing], , cmp, Ordering[B], B >: Nothing (B Nothing. , - Nothing , , ).

0
source

All Articles