- Scala Functional Programming Patterns
- Atul S. Khot
- 417字
- 2021-07-30 09:44:25
Tail recursion to the rescue
There is a technique, an optimization really, that helps us get out of the logjam. However, we need to tweak the code a bit for this. We will make the recursive call as the last and only call. This means that there is no intermediate context to remember. This last and only call is called the tail call. Code in this tail call form is amenable to TCO. Scala generates code that, behind the scenes, uses a loop—the generated code does not use any stack frames:
import scala.annotation.tailrec def count(list: List[Int]): Int = { @tailrec // 1 def countIt(l: List[Int], acc: Int): Int = l match { case Nil => acc // 2 case head :: tail => countIt(tail, acc+1) // 3 } countIt(list, 0) }
The changes are like this:
We have a nested workhorse method that is doing all the hard work. The count
method calls the countIt
nested recursive method, with the list it got in the argument, and an accumulator. The earlier intermediate context is now expressed as an accumulator expression with the help of the following steps:
- The
@tailrec
annotation makes sure that we are doing the right things so that we benefit from the TCO. Without@tailrec
, Scala may apply the optimization or it may not. The@tailrec
annotation is a helping hand to ensure that the function call is optimized. Try the same annotation on our first version. You will get a compilation error. - Play time: Change the second case in the previous code as shown:
case head :: tail => { val cnt: Int = countIt(tail, acc + 1) println(cnt) cnt }
- You will get a compilation error after changing the second case:
Error: could not optimize @tailrec annotated method countIt: it contains a recursive call not in tail position
- When the execution lands in this clause, we are at the end of the list. We are not going to find any more elements, so the base case just returns the accumulator.
- There is no intermediate context now—just a tail call. This is the only and last recursive call. We found one more element. We increment the accumulator to record the fact and pass it on.
Compared to the earlier version, why does this version work? If the compiler can use tail call optimization, then it does not need to stack up the context. So, no stack frames are needed as the resulting executable code uses loops behind the scenes.
- 造個小程序:與微信一起干件正經事兒
- MySQL 8從入門到精通(視頻教學版)
- LabVIEW入門與實戰開發100例
- PostgreSQL技術內幕:事務處理深度探索
- WSO2 Developer’s Guide
- Learning Firefox OS Application Development
- Effective Python Penetration Testing
- 數據結構習題解析與實驗指導
- 編程菜鳥學Python數據分析
- OpenGL Data Visualization Cookbook
- 快速入門與進階:Creo 4·0全實例精講
- 軟件體系結構
- Java并發編程:核心方法與框架
- ROS機器人編程實戰
- 3D Printing Designs:Octopus Pencil Holder