Scala:如何避免在这里使用var [英] Scala: How to avoid var here
本文介绍了Scala:如何避免在这里使用var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的代码段:
I have a code snippet like this:
def until(terminationCond: List[A]=>Boolean, combiner: List[A]=>List[A] )(obj: List[A]): A = {
var tempObj = obj
while(!terminationCond(tempObj)) {
tempObj = combiner(obj)
}
tempObj.head
}
我正在寻找一种以功能编程样式编写此代码的方法,从而避免使用任何 mutable 类型.
I am looking out a way to write this code from functional programming style, avoiding any mutable types.
推荐答案
我发现以下内容比显式递归版本更具声明性:
I find the following a little more declarative than the explicitly recursive version:
def until[A](
terminationCond: List[A] => Boolean,
combiner: List[A] => List[A]
)(obj: List[A]): A =
Stream.iterate(obj)(combiner).dropWhile(!terminationCond(_)).head.head
即我们通过迭代地应用combiner
来创建结果流,只要不满足终止条件就将其丢弃,然后返回它所针对的第一个对象的头部.
I.e. we create a stream of results by iteratively applying combiner
, drop as long as the termination condition doesn't hold, and then return the head of the first for which it does.
这篇关于Scala:如何避免在这里使用var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文