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

后端 未结 10 956
别那么骄傲
别那么骄傲 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:37

    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)

提交回复
热议问题