Functional style early exit from depth-first recursion

前端 未结 3 2044
清歌不尽
清歌不尽 2021-02-08 18:52

I have a question about writing recursive algorithms in a functional style. I will use Scala for my example here, but the question applies to any functional language.

I

3条回答
  •  长情又很酷
    2021-02-08 19:51

    You can convert breadth into depth by passing along an index or taking the tail:

    def suml(xs: List[Int], total: Int = 0) = xs match {
      case Nil => total
      case x :: rest => suml(rest, total+x)
    }
    
    def suma(xs: Array[Int], from: Int = 0, total: Int = 0) = {
      if (from >= xs.length) total
      else suma(xs, from+1, total + xs(from))
    }
    

    In the latter case, you already have something to limit your breadth if you want; in the former, just add a width or somesuch.

提交回复
热议问题