问题
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
}
I am looking out a way to write this code from functional programming style, avoiding any mutable types.
回答1:
Using recursion:
@tailrec
def doUntilTerm(obj: List[A]) =
if (terminationCond(obj)) obj.head else doUntilTerm(obj)
回答2:
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
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.
来源:https://stackoverflow.com/questions/39643246/scala-how-to-avoid-var-here