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

后端 未结 10 955
别那么骄傲
别那么骄傲 2021-01-31 14:03

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 leastOrNo         


        
10条回答
  •  走了就别回头了
    2021-01-31 14:22

    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
    

提交回复
热议问题