当前位置:网站首页>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.🥸
边栏推荐
- 中信证券网上开户怎么开的?安全吗?
- Chapter 5 C programming expert thinking 5.4 alert Interpositioning of links
- 结构体指针知识要点总结
- [Ryerson emotional speaking/singing audiovisual dataset (RAVDESS)]
- C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.4 使声明与定义相匹配
- This Thursday evening at 19:00, the fourth live broadcast of knowledge empowerment丨The realization of equipment control of OpenHarmony smart home project
- 技术解析|如何将 Pulsar 数据快速且无缝接入 Apache Doris
- 3000 words, is take you understand machine learning!
- Tensors - Application Cases
- PHP高级开发案例(1):使用MYSQL语句跨表查询无法导出全部记录的解决方案
猜你喜欢

Explain详解与实践

manipulation of file contents

3000 words, is take you understand machine learning!

Implementing a server-side message active push solution based on SSE

See how DevExpress enriches chart styles and how it empowers fund companies to innovate their business

详解八大排序

帮助企业实现数字化转型成功的八项指导原则

System design. Seckill system

【云原生--Kubernetes】Pod资源管理与探针检测

【C语言进阶】程序环境和预处理
随机推荐
A Preliminary Study of RSS Subscription to WeChat Official Account-feed43
如何简化现代电子采购的自动化?
Towards Real-Time Multi-Object Tracking(JDE)
Eight guiding principles to help businesses achieve digital transformation success
For Qixi Festival, I made a confession envelope with code
3000 words, is take you understand machine learning!
Mobile payment online and offline payment scenarios
7. The principle description of LVS load balancing cluster
2022软件测试面试题 最新字节跳动50道真题面试题 刷完已拿下15k 附讲解+答疑
[Skill] Using Sentinel to achieve priority processing of requests
八年软件测试工程师带你了解-测试岗进阶之路
附加:对于“与数据表对应的实体类“,【面对MongoDB时,使用的@Id等注解】和【以前面对MySQL时,使用的@Id等注解】,是不同的;
结构体函数练习
图像处理之Bolb分析(一)
数据治理平台项目总结和分析
2.15 keil使用电脑端时间日期
share总结
How to simplify the automation of modern e-procurement?
系统设计.如何设计一个秒杀系统(完整版 转)
Jenkins 导出、导入 Job Pipeline