我正在学习 Scala,我想知道使用 Scala 的函数式编程功能表达这种命令式模式的最佳方式。
def f(l: List[Int]): Boolean = {
for (e <- l) {
if (test(e))
return true
}
}
return false
}
我能想到的最好的方法是:
l map { e => test(e) } contains true
但这效率较低,因为它在每个元素上调用 test(),而命令式版本在满足 test() 的第一个元素上停止。我可以使用更惯用的函数式编程技术来达到同样的效果吗?命令式版本在 Scala 中似乎很尴尬。
最佳答案
您可以使用exists方法:
val listWithEvens = List(1,2,3,4)
val listWithoutEvens = List(1,3,5)
def test(e: Int) = e % 2 == 0
listWithEvens.exists(test(_)) // true
listWithoutEvens.exists(test(_)) // false
// alternative
listWithEvens.exists(_ % 2 == 0) // true
如果你不熟悉像这样使用的 _,它相当于:
listWithEvens.exists(v => v % 2 == 0)
关于scala - 以下命令式代码最有效的功能版本是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4523812/