我有一组项,让我们称之为Effect,我有一个Cause列表,其中包含一组possibleEffects : Set[Effect]
我需要迭代效果列表,并且只返回我为每个Cause找到的第一个Effect。可能有重叠的原因导致多个影响,这就是为什么结果需要在一个集合中。我需要它尽可能快,因为它执行了很多次。我想出了以下内容(不确定这是否是最好的方法,我对scala还不熟悉)。
我正在尝试使用find()方法,它返回一个Option[Cause]。有没有办法过滤掉返回None的那些(在现实中不会发生,在列表中总是有原因,除非我有一个bug),并从其中的一些单子中提取它以便于理解?我似乎无法在其中使用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发布于 2013-12-10 14:01:04
因为您可以在“理解”中迭代选项,所以可以将"=“更改为"<-”,这将给出与flatten相同的结果。
val firstCauses : Set[Cause] = (for {
effect <- effects
possibleCause <- allCauses.find(_.possibleEffects.contains(effect))
} yield possibleCause)发布于 2013-12-10 13:31:59
您不需要过滤返回None的那些。可以使用Set[Option[T]]方法将Set[T]转换为flatten。这将为您摆脱None:
> 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)因此,为了明确起见,您可以在您的理解中使用yield Option,并且只需对结果进行flatten。
https://stackoverflow.com/questions/20494643
复制相似问题