当前位置:网站首页>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
)
T
Type of the incoming parameter;R
is 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.🥸
边栏推荐
- 7-2 LVS+DR概述与部署
- Embedded database development programming MySQL (full)
- 结构体指针知识要点总结
- C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.5 数组和指针的其他区别
- Bolb analysis of image processing (1)
- See how DevExpress enriches chart styles and how it empowers fund companies to innovate their business
- 2022年软件测试——精选金融银行面试真题
- Stop behind.
- Shocked, 99.9% of the students didn't really understand the immutability of strings
- Cache pool of unity framework
猜你喜欢
Mini program + e-commerce, fun new retail
There is an 8 hour difference between the docker installation of mysql and the host.
JVM笔记
Structure function exercise
10 Convolutional Neural Networks for Deep Learning 3
【机器学习】21天挑战赛学习笔记(一)
某母婴小程序加密参数解密
ADC噪声全面分析 -03- 利用噪声分析进行实际设计
Take care of JVM performance optimization (own note version)
软件测试如何系统规划学习呢?
随机推荐
Metaverse "Drummer" Unity: Crazy expansion, suspense still exists
七夕节,我用代码制作了表白信封
【流程图】
How to dynamically add script dependent scripts
Jenkins 导出、导入 Job Pipeline
路网编辑器技术预研
Chapter 5 C programming expert thinking 5.4 alert Interpositioning of links
QT 如何识别文件的编码格式
The video of machine learning to learn [update]
Eight guiding principles to help businesses achieve digital transformation success
2023年PMP考试会用新版教材吗?回复来了!
如何简化现代电子采购的自动化?
7-3 LVS+Keepalived Cluster Description and Deployment
Take care of JVM performance optimization (own note version)
How to keep the source code confidential in the development under the burning scenario
2022 software test interview questions The latest ByteDance 50 real interview questions, 15k have been won after brushing, with explanation + Q&A
DataTable uses Linq for grouping and summarization, and converts the Linq result set into DataTable
Learn iframes and use them to solve cross-domain problems
附加:对于“与数据表对应的实体类“,【面对MongoDB时,使用的@Id等注解】和【以前面对MySQL时,使用的@Id等注解】,是不同的;
8. Haproxy builds a web cluster