12

私は を持っていて、それらの のIterator[Option[T]]を取得したいです。これよりも良い方法があるはずです:Iterator[T]OptionT isDefined

it filter { _ isDefined} map { _ get }

私はそれが1つの構成で可能だと思っていたでしょう...誰か何かアイデアはありますか?

4

4 に答える 4

15

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
于 2009-03-20T22:11:35.813 に答える
11

新しいバージョンでは、これが可能になりました:

val it: Iterator[Option[T]] = ...
val flatIt = it.flatten
于 2011-02-21T13:15:42.223 に答える
5

これは私にとってはうまくいきます(Scala 2.8):

it.collect {case Some(s) => s}
于 2011-02-24T19:17:29.047 に答える
3

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).

于 2011-04-25T14:19:48.107 に答える