[英]Functional code for looping with early exit
如何以函数式风格重构此代码(scala 惯用)
def findFirst[T](objects: List[T]):T = {
for (obj <- objects) {
if (expensiveFunc(obj) != null) return obj
}
null.asInstanceOf[T]
}
这几乎正是find
方法所做的,只是它返回一个Option
。 因此,如果您想要这种确切的行为,您可以添加对Option.orNull
的调用,如下所示:
objects.find(expensiveFunc).orNull
首先,不要在 Scala 中使用null
(与 Java 代码交互时除外)而是 Options。 其次,用递归替换循环。 第三,看看 Scala 功能丰富的 API ,您正在寻找的方法已经存在,正如sepp2k指出的那样。
为了学习 puprose 你的例子可以重写为:
def findFirst[T](objects: List[T]):Option[T] = objects match {
case first :: rest if expensiveFunc( first ) != null => Some( first )
case _ :: rest => findFirst( rest )
case Nil => None
}
折叠怎么样?
我们以某种方式伪昂贵的 function:
scala> def divByFive (n: Int) : Option[Int] = {
| println ("processing " + n)
| if (n % 5 == 0) Some (n) else None }
divByFive: (n: Int)Option[Int]
弃牌期权:
scala> ((None: Option[Int]) /: (1 to 11)) ((a, b) =>
| if (a != None) a else divByFive (b))
processing 1
processing 2
processing 3
processing 4
processing 5
res69: Option[Int] = Some(5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.