当前位置:网站首页>Interesting Kotlin 0x0E: DeepRecursiveFunction
Interesting Kotlin 0x0E: DeepRecursiveFunction
2022-08-04 04:46:00 【AndroidKt】
前言
DeepRecursiveFunction 是 Kotlin 在 1.4.0 The version attempts to resolve deep recursion StackOverflowError A trial solution to the problem.在最新发布的 1.7.0 official version Stable.Facing the stack overflow problem due to recursion,Generally we use two solutions:
- 增加栈大小
- 改写代码,采用非递归方式实现
Kotlin 通过定义 DeepRecursiveFunction Deep recursive types to implement non-recursive rewriting.
官方建议:Recursive depth operation 1000 考虑使用 DeepRecursiveFunction.(Consider using deep recursive functions in your code where your recursion depth exceeds 1000 calls.)
语法
定义
public class DeepRecursiveFunction<T, R>(
internal val block: suspend DeepRecursiveScope<T, R>.(T) -> R
)
TType of the incoming parameter;Ris the output result type;block函数体.
调用
public abstract suspend fun callRecursive(value: T): R
用于“递归”调用DeepRecursiveFunction
public operator fun DeepRecursiveFunction<*, *>.invoke(value: Any?): Nothing
操作符重载,以便 DeepRecursiveFunction 可以通过()操作符调用,Of course, you can also choose to call directlyinvoke函数.
Look at the official example comparison,可能更直观一点.
示例
Implement the depth calculation of the binary tree:原始递归DeepRecursiveFunction.
原始递归
fun depth(t: Tree?): Int =
if (t == null) 0 else maxOf(
depth(t.left), // recursive call one
depth(t.right) // recursive call two
) + 1
DeepRecursiveFunction
val calculateDepth = DeepRecursiveFunction<Tree?, Int> {
t ->
if (t == null) 0 else maxOf(
callRecursive(t.left),
callRecursive(t.right)
) + 1
}
It can be seen by comparing the above two codes,Developers can easily rewrite from the original recursive way DeepRecursiveFunction 方式.这就是 Kotlin The desired effect of low development costs.The recursion level is too deep when developers use primitive recursion StackOverflowError问题时, easy to adjust to DeepRecursiveFunction ,It can help developers quickly solve stack overflow problems on the premise of avoiding a lot of code rewriting.
Run
fun main() {
// Generate a tree with a depth of 100_000
val deepTree = generateSequence(Tree(null, null)) {
prev ->
Tree(prev, null)
}.take(4).last()
println(calculateDepth(deepTree)) // 100000
println(depth(deepTree)) // 100000
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LPAOp9KH-1659446563474)(http://qiniu.fultter.club/image-20220731130252997.png)]
源码
关于 DeepRecursiveFunction The source code is all concentrated in DeepRecursive.kt文件中,There are mainly three categories:
- DeepRecursiveFunction
- DeepRecursiveScope
- DeepRecursiveScopeImpl
The specific implementation focuses on DeepRecursiveScopeImpl 类中,The recursive logic is implemented through the coroutine mechanism.
suspend Simulates pushing down the stack ️,resume Simulates popping up the stack ️,To achieve an effect similar to recursive calls🪆.
结语
Behind every piece of syntactic sugar,总有几个 Kotlin of engineers are carrying the weight for us.🥸
边栏推荐
- 2022 Hangzhou Electric Power Multi-School League Game 5 Solution
- 烧录场景下开发如何进行源代码保密工作
- DataTable uses Linq for grouping and summarization, and converts the Linq result set into DataTable
- 7-2 LVS+DR概述与部署
- SVM介绍以及实战
- 7-1 LVS+NAT load balancing cluster, NAT mode deployment
- 基于gRPC编写golang简单C2远控
- 3000 words, is take you understand machine learning!
- This Thursday evening at 19:00, the fourth live broadcast of knowledge empowerment丨The realization of equipment control of OpenHarmony smart home project
- 帮助企业实现数字化转型成功的八项指导原则
猜你喜欢

7-1 LVS+NAT load balancing cluster, NAT mode deployment

10 Convolutional Neural Networks for Deep Learning 3

This Thursday evening at 19:00, the fourth live broadcast of knowledge empowerment丨The realization of equipment control of OpenHarmony smart home project

详解八大排序

For Qixi Festival, I made a confession envelope with code

SQL interview Questions

关于yolo7和gpu

7-2 LVS+DR Overview and Deployment

SQL query String field less than 10 how to check

System design. Seckill system
随机推荐
Introduction to mq application scenarios
QT 如何识别文件的编码格式
备份工具pg_dump的使用《postgres》
Learn iframes and use them to solve cross-domain problems
小程序 + 电商,玩转新零售
如何动态添加script依赖的脚本
Basic characteristics of TL431 and oscillator circuit
7-1 LVS+NAT load balancing cluster, NAT mode deployment
day13--postman接口测试
Deep learning -- CNN clothing image classification, for example, discussed how to evaluate neural network model
解决问题遇到的问题
PL/SQL Some Advanced Fundamental
【SemiDrive源码分析】【MailBox核间通信】47 - 分析RPMSG_IPCC_RPC 方式 单次传输的极限大小 及 极限带宽测试
Uni-app 小程序 App 的广告变现之路:全屏视频广告
Explain detailed explanation and practice
结构体函数练习
ADC噪声全面分析 -03- 利用噪声分析进行实际设计
TL431的基本特性以及振荡电路
信息学奥赛一本通 1312:【例3.4】昆虫繁殖
[21 Days Learning Challenge] Image rotation problem (two-dimensional array)