Functional code for looping with early exit

旧街凉风 提交于 2019-12-20 10:29:05

问题


How can I refactor this code in functional style (scala idiomatic)

def findFirst[T](objects: List[T]):T = {
  for (obj <- objects) {
    if (expensiveFunc(obj) != null) return obj
  }
  null.asInstanceOf[T]
}

回答1:


This is almost exactly what the find method does, except that it returns an Option. So if you want this exact behavior, you can add a call to Option.orNull, like this:

objects.find(expensiveFunc).orNull



回答2:


First, don't use null in Scala (except when interacting with Java code) but Options. Second, replace loops with recursion. Third, have a look at the rich API of Scala functions, the method you are looking for already exists as pointed by sepp2k.

For learning puprose your example could be rewritten as:

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
}



回答3:


How about a fold?

Our somehow pseudo-expensive function:

scala> def divByFive (n: Int) : Option[Int] = {
     | println ("processing " + n)               
     | if (n % 5 == 0) Some (n) else None } 
divByFive: (n: Int)Option[Int]   

Folding on an Option:

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)


来源:https://stackoverflow.com/questions/6729785/functional-code-for-looping-with-early-exit

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