How to find min () or max () from two options [Int]

How would you find minValuebelow? I have my own solution, but I want to see how others will do it.

val i1: Option[Int] = ...
val i2: Option[Int] = ...
val defaultValue: Int = ...
val minValue = ?
+6
source share
8 answers

I think this is what you need:

val minValue = List(i1, i2).flatten match {
  case Nil => defaultValue
  case xs => xs.min
}

I would avoid it sorted, since sorting requires a lot more processing than just looking for max or min (although it probably doesn't matter much in this case).

+3
source

: , , -: , , , None, , ( min) ( max), - .

: i1 - Some(1) i2 - None, , 1.

, Option[A] Int. , Scalaz 7 :

import scalaz._, Scalaz._

optionMonoid(Semigroup.minSemigroup[Int]).append(i1, i2) getOrElse defaultValue

:

Tags.Min(i1) |+| Tags.Min(i2) getOrElse defaultValue

, , , .


, :

(for { x <- i1; y <- i2 } yield math.min(x, y)) getOrElse defaultValue

, :

i1.flatMap(x => i2.map(math.min(x, _))) getOrElse defaultValue

, , - "" (min) (Option). Scalaz :

import scalaz._, Scalaz._

(i1 |@| i2)(math.min) getOrElse defaultValue

, , .

+8
val minValue: Int = List(i1, i2).flatten.sorted.headOption getOrElse defaultValue
+3

, . , , API Option.orElse.

val a: Option[Int]  = Some(10)
val b: Option[Int] = Some(20)
val c: Option[Int] = (a, b) match {
  case (Some(x), Some(y)) => Some(x min y)
  case (x, y) => x orElse y
}
+3

, , , .

(for (Some(x) <- List(None, Some(3))) yield x) max

, List.flatten, .

+2

scalaz map/for/getOrElse, :

val minValue = (i1, i2) match {
  case (Some(x), Some(y)) => math.min(x, y)
  case _ => defaultValue
}
+1

, , reduceLeftOption ( math.max math.min ):

val min = (first ++ second).reduceLeftOption(math.min).getOrElse(defaultValue)

scala> val first = Some(10)
first: Some[Int] = Some(10)

scala> val second: Option[Int] = None
second: Option[Int] = None

scala> val defaultMin = -1
defaultMin: Int = -1

scala> (first ++ second).reduceLeftOption(math.min).getOrElse(defaultMin)
res7: Int = 10

scala> val first: Option[Int] = None
first: Option[Int] = None

scala> (first ++ second).reduceLeftOption(math.min).getOrElse(defaultMin)
res8: Int = -1

scala> val first = Some(10)
first: Some[Int] = Some(10)

scala> val second = Some(42)
second: Some[Int] = Some(42)

scala> (first ++ second).reduceLeftOption(math.min).getOrElse(defaultMin)
res9: Int = 10
+1

We can combine Option2 as Iterablewith the operator Option : A, That] (that: scala.collection.GenTraversableOnce [B]) (implicitbf: scala.collection.generic.CanBuildFrom [Repr, B, That]): That rel = "nofollow noreferrer ">++ , which allows us to use (to handle the case of an empty iterable, case-formed ) and the default value, if necessary, with : minOption minOptionNone/NonegetOrElsegetOrElse

(optionA ++ optionB).minOption.getOrElse(-1)
// None and None       => -1
// Some(5) and None    => 5
// None and Some(5)    => 5
// Some(5) and Some(3) => 3
0
source

All Articles