Scala: How to avoid var here

流过昼夜 提交于 2019-12-11 05:26:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!