如何在Scala中优化此方法?

问题描述 投票:2回答:2

假设我有A方法的foo类:

class A(x: Int) { def foo(): Option[Int] = if (x > 0) Some(x) else None }

现在我正在编写函数bar,如下所示:

def bar(as: List[A]): Option[(A,  Int)] = for {
  a <- as.view.find(_.foo.nonEmpty)
  foo <- a.foo
} yield (a, foo)

上面的代码工作正常,但它为找到的foo实例两次调用A方法。如何重新编写bar只为找到的foo实例调用方法A一次?

scala sequence option
2个回答
1
投票
 as.iterator.flatMap { a => a.foo.map { a -> _ } }.find(_ => true)

1
投票

使用流。流中的元素被懒惰地评估。

def bar(as: List[A]): Option[(A, Int)] = {
  as
    .toStream
    .map(x => (x, x.foo()))
    .find(z => z._2.isDefined)
    .map(p => (p._1, p._2.get))
}
© www.soinside.com 2019 - 2024. All rights reserved.