Convert normal recursion to tail recursion

后端 未结 6 774
悲哀的现实
悲哀的现实 2020-12-13 07:30

I was wondering if there is some general method to convert a \"normal\" recursion with foo(...) + foo(...) as the last call to a tail-recursion.

For exa

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 08:14

    I don't know how theoretical this question is, but a recursive implementation won't be efficient even with tail-recursion. Try computing pascal(30, 60), for example. I don't think you'll get a stack overflow, but be prepared to take a long coffee break.

    Instead, consider using a Stream or memoization:

    val pascal: Stream[Stream[Long]] = 
      (Stream(1L) 
        #:: (Stream from 1 map { i => 
          // compute row i
          (1L 
            #:: (pascal(i-1) // take the previous row
                   sliding 2 // and add adjacent values pairwise
                   collect { case Stream(a,b) => a + b }).toStream 
            ++ Stream(1L))
        }))
    

提交回复
热议问题