私は を持っていて、それらの のIterator[Option[T]]
を取得したいです。これよりも良い方法があるはずです:Iterator[T]
Option
T
isDefined
it filter { _ isDefined} map { _ get }
私はそれが1つの構成で可能だと思っていたでしょう...誰か何かアイデアはありますか?
私は を持っていて、それらの のIterator[Option[T]]
を取得したいです。これよりも良い方法があるはずです:Iterator[T]
Option
T
isDefined
it filter { _ isDefined} map { _ get }
私はそれが1つの構成で可能だと思っていたでしょう...誰か何かアイデアはありますか?
it
の場合Iterable
val it:Iterable[Option[T]] = ...
it.flatMap( x => x ) //returns an Iterable[T]
it
の場合Iterator
val it:Iterator[Option[T]] = ...
it.flatMap( x => x elements ) //returns an Iterator[T]
it.flatMap( _ elements) //equivalent
新しいバージョンでは、これが可能になりました:
val it: Iterator[Option[T]] = ...
val flatIt = it.flatten
これは私にとってはうまくいきます(Scala 2.8):
it.collect {case Some(s) => s}
To me, this is a classic use case for the monadic UI.
for {
opt <- iterable
t <- opt
} yield t
It's just sugar for the flatMap
solution described above, and it produces identical bytecode. However, syntax matters, and I think one of the best times to use Scala's monadic for
syntax is when you're working with Option
, especially in conjunction with collections.
I think this formulation is considerably more readable, especially for those not very familiar with functional programming. I often try both the monadic and functional expressions of a loop and see which seems more straightforward. I think flatMap is hard name for most people to grok (and actually, calling it >>=
makes more intuitive sense to me).