3

我有一组项目,让我们调用它们Effect,我有一个列表,Cause其中包含一组possibleEffects : Set[Effect]

我需要遍历效果列表,只返回Cause我为每个效果找到的第一个Effect。可能有重叠的原因会导致多个结果,这就是结果需要放在一个集合中的原因。我需要它尽可能快,因为它执行了很多次。我想出了以下方法(不确定这是否是最好的方法,我是 scala 的新手)。

我正在尝试使用find()返回Option[Cause]. 有没有办法过滤掉那些返回的None(实际上不会发生,列表中总会有原因,除非我有错误),然后从 for 理解中的 Some monad 中提取它?我似乎无法在matches其中使用。

  val firstCauses : Set[Cause] = (for {
             effect <- effects
             possibleCause = allCauses.find(_.possibleEffects.contains(effect))
             //todo: filter out possibleCause if it is not Some(Cause), and get it out of the Some monad so that the yield takes it
           } yield possibleCause).toSet
4

2 回答 2

4

因为您可以在理解中迭代 Option,所以您可以将“=”更改为“<-”,这将为您提供与 flatten 相同的结果

val firstCauses : Set[Cause] = (for {
     effect <- effects
     possibleCause <- allCauses.find(_.possibleEffects.contains(effect))
} yield possibleCause)
于 2013-12-10T14:01:04.993 回答
3

您不需要过滤返回的那些None。您可以使用该方法将 aSet[Option[T]]变为 a 。这将为您摆脱:Set[T]flattenNone

> val s = Set(Some(1), None, Some(2), None,Some(3) )
s: scala.collection.immutable.Set[Option[Int]] = Set(Some(1), None, Some(2), Some(3))
> s.flatten
res1: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

所以,要清楚,你可以yieldOption你的理解和flatten结果中。

于 2013-12-10T13:31:59.243 回答