2014-05-08 54 views

回答

6
optionIterator find { case Some(x) if predicate(x) => true case _ => false } 

至於無視例外...它是謂語,可以throw ?因爲這不是很明智。儘管如此...

optionIterator find { 
    case Some(x) => Try(predicate(x)) getOrElse false 
    case _  => false 
} 
+0

或'嘗試(P(X))getOrElse返回FALSE。 –

+0

是的,那樣更好。我已經更新了答案以反映它。 –

1

假設你可以用你的斷言,這樣的錯誤返回false:

iterator.flatMap(x => x).find(yourSafePredicate) 

flatMap需要集合的集合(其中Option可迭代是作爲OptionEither被認爲是與一個的最大大小的集合),並將其轉換成一個單一的集合:

scala> for { x <- 1 to 3; y <- 1 to x } yield x :: y :: Nil 
res30: IndexedSeq[List[Int]] = Vector(List(1, 1), List(2, 1), List(2, 2), List(3, 1), List(3, 2), List(3, 3)) 

scala> res30.flatMap(x => x) 
res31: IndexedSeq[Int] = Vector(1, 1, 2, 1, 2, 2, 3, 1, 3, 2, 3, 3) 

find返回的迭代,一個謂語爲OptionNone匹配的第一個條目;如果沒有匹配:

scala> (1 to 10).find(_ > 3) 
res0: Option[Int] = Some(4) 

scala> (1 to 10).find(_ == 11) 
res1: Option[Int] = None 
3

添加的最佳地道一件大衣的油漆工作:

scala> val vs = (0 to 10) map { case 3 => None case i => Some(i) } 
vs: scala.collection.immutable.IndexedSeq[Option[Int]] = Vector(Some(0), Some(1), Some(2), None, Some(4), Some(5), Some(6), Some(7), Some(8), Some(9), Some(10)) 

scala> def p(i: Int) = if (i % 2 == 0) i > 5 else ??? 
p: (i: Int)Boolean 

scala> import util._ 
import util._ 

scala> val it = vs.iterator 
it: Iterator[Option[Int]] = non-empty iterator 

scala> it collectFirst { case Some(i) if Try(p(i)) getOrElse false => i } 
res2: Option[Int] = Some(6) 

獲得過五第一偶數不炸掉測試。

1

一些樣本數據

scala> val l = Seq(Some(1),None,Some(-7),Some(8)) 
l: Seq[Option[Int]] = List(Some(1), None, Some(-7), Some(8)) 

使用上的選項的序列flatMap會產生一個序列定義值,所有的無的都將被丟棄

scala> l.flatMap(a => a) 
res0: Seq[Int] = List(1, -7, 8) 

然後用發現 - 您將獲得滿足謂詞的第一個值。請注意,發現的值被封裝爲選項,導致找到應該能夠在「未找到」情況下返回有效值(無)值。

scala> l.flatMap(a => a).find(_ < 0) 
res1: Option[Int] = Some(-7) 

據我所知,這是「好」的方式爲斯卡拉。

可能更習慣用法是使用收集/collectFirst在Seq ...

scala> l.collectFirst { case [email protected](x) if x < 0 => a } 
res2: Option[Some[Int]] = Some(Some(-7)) 

注重的是,這裏我們有一些(部分(-7)),因爲collectFind應該有機會產生「未找到」的值,所以在這裏第1部分 - 從collectFirst,第二部分 - 從Option的Seq的源元素。

你可以拉平一些(一些(-7))如果你需要在你的手中的價值。

scala> l.collectFirst({ case [email protected](x) if x < 0 => a }).flatten 
res3: Option[Int] = Some(-7) 

如果沒有找到 - 你將擁有無

scala> l.collectFirst({ case [email protected](x) if x < -10 => a }).flatten 
res9: Option[Int] = None 
+0

問題是關於迭代器的。 –