【Coroutines】Implement Python Generator by Kotlin Coroutines

Expected

a generator object that can generate sequence objects

and only generate object when consumer object request for it

kotlin 复制代码
fun main() {
    val generator = generator {
        yield(100)
        yield(200)
        yield(300)
    }
    while (generator.hasNext()) {
        val value = generator.await()
        println(value)
    }
}
Implementation
kotlin 复制代码
package com.code.kotlin

import kotlin.coroutines.*

@RestrictsSuspension
interface GeneratorScope<T> {

    suspend fun yield(value: T)
}

interface GeneratorIterator<T> : Iterator<T> {

    fun await(): T
}

internal interface Generator<T> : GeneratorScope<T>, GeneratorIterator<T>, Continuation<Any>

internal sealed class GeneratorState<T> {
    class WAITING<T>(val continuation: Continuation<Unit>) : GeneratorState<T>()
    class READY<T>(val continuation: Continuation<Unit>, val value: T) : GeneratorState<T>()
    class COMPLETED<T> : GeneratorState<T>()
}

internal class GeneratorImpl<T> : Generator<T> {

    override val context: CoroutineContext = EmptyCoroutineContext

    internal lateinit var state: GeneratorState<T>

    override suspend fun yield(value: T) {
        suspendCoroutine { continuation ->
            when (val _state = state) {
                is GeneratorState.WAITING -> {
                    state = GeneratorState.READY(continuation, value)
                }
                is GeneratorState.READY,
                is GeneratorState.COMPLETED -> throw IllegalStateException()
            }
        }
    }

    override fun resumeWith(result: Result<Any>) {
        state = GeneratorState.COMPLETED()
    }

    private fun resume() {
        when (val _state = state) {
            is GeneratorState.WAITING -> {
                _state.continuation.resume(Unit)
            }
            else -> {}
        }
    }

    override fun hasNext(): Boolean {
        resume()
        return state !is GeneratorState.COMPLETED
    }

    override fun next(): T {
        when (val _state = state) {
            is GeneratorState.READY -> {
                state = GeneratorState.WAITING(_state.continuation)
                return _state.value
            }
            is GeneratorState.WAITING,
            is GeneratorState.COMPLETED -> throw IllegalStateException()
        }
    }

    override fun await() = next()
}

fun <T> generator(
    block: suspend GeneratorScope<T>.() -> Unit
): GeneratorIterator<T> {
    val generator = GeneratorImpl<T>()
    val continuation = block.createCoroutine(generator, generator)
    generator.state = GeneratorState.WAITING(continuation)
    return generator
}
相关推荐
查理零世18 分钟前
保姆级讲解 python之zip()方法实现矩阵行列转置
python·算法·矩阵
刀客12329 分钟前
python3+TensorFlow 2.x(四)反向传播
人工智能·python·tensorflow
sysu632 小时前
95.不同的二叉搜索树Ⅱ python
开发语言·数据结构·python·算法·leetcode·面试·深度优先
SsummerC2 小时前
【leetcode100】从前序与中序遍历序列构造二叉树
python·算法·leetcode
陌北v12 小时前
PyTorch广告点击率预测(CTR)利用深度学习提升广告效果
人工智能·pytorch·python·深度学习·ctr
Мартин.3 小时前
[Meachines] [Easy] Bashed PHP Bash+Python计划任务权限提升
python·php·bash
码界筑梦坊3 小时前
基于Flask的旅游系统的设计与实现
python·flask·毕业设计·旅游
闲暇部落3 小时前
kotlin内联函数——takeIf和takeUnless
android·kotlin
张云瀚3 小时前
《Kotlin核心编程》下篇
kotlin·kotlin核心编程
辞落山4 小时前
自定义数据集使用scikit-learn中的包实现线性回归方法对其进行拟合
python·线性回归·scikit-learn