safe Iterator.max
Is there a library that offers a function like Iterator.max开发者_Python百科
, but that returns an Option[A]
rather than an A
to account for possibly-empty iterators? Alternately, is there a library that offers a class PosInf[A]
or so that adjoins a positive infinity to A
?
(Obviously either of these is mere gruntwork to do myself, but using a library is almost always preferable to duplicating code.)
scalaz: MA.maximum
. Usage:
import scalaz._; import Scalaz._
List(1, 2, 3).maximum == Some(3)
List.empty[Int].maximum == None
the only problem is that this does not work with Iterators directly, so you would have to use a Stream
instead (e.g. using Iterator.toStream
)
List(1, 2, 3).iterator.toStream.maximum = Some(3)
I'm not aware of anything but this is simple:
def maxOpt[T: Numeric](i: Iterator[T]) = if (i.hasNext) Some(i.max) else None
Edit: Numeric is too strong a requirement, Ordering is enough:
def maxOpt[T: Ordering](i: Iterator[T]) = if (i.hasNext) Some(i.max) else None
And if you use isEmpty
is should work on any subclass of TraversableOnce
精彩评论