前两天给 Ice 加了 call/cc, 为此还重构了一波, 实现 call/cc 还是因为看了轮子哥的大专系列(

里边说提供 continuation 语言实现 Coroutine 起来很轻松, 后来又查了一些资料, 都说 continuation 表达能力很强, 就实现了一手, 调用方式完全等同 call/cc, 既然是看 Coroutine 才要实现 call/cc, 那实现了之后当然要用 call/cc 实现一手 Coroutine 了(

不过这个 Coroutine 比较简陋, 只提供 create, resume, yield, destroy

coroutine: (@() {
@funcs: [];
@conts: [];
@deletes: [];
@co_cont: none; @create(func) {
if deletes.empty() {
@id: funcs.size();
funcs.push(func);
conts.push(none);
return id;
} else {
@id: deletes.pop();
funcs[id]: func;
conts[id]: none;
return id;
}
} @resume(id) {
if conts[id] = none {
conts[id]: call_with_current_continuation(@(cont) {
co_cont: cont;
funcs[id]();
});
} else {
conts[id]: call_with_current_continuation(@(cont) {
co_cont: cont;
conts[id](none);
});
}
} @yield() {
call_with_current_continuation(co_cont);
} @destroy(id) {
funcs[id]: conts[id]: none;
deletes.push(id);
} return @() {};
})();

测试一下:

@foo() {
@i: 0;
while i < 5 {
println(i: i + 1);
coroutine.yield();
}
} @id1: coroutine.create(foo);
@id2: coroutine.create(foo); @i: 0;
while i < 5 {
coroutine.resume(id1);
coroutine.resume(id2);
i: i + 1;
} coroutine.destroy(id1);
coroutine.destroy(id2);

输出

1
1
2
2
3
3
4
4
5
5

里边唯一我觉得有点意思的地方是 resume 里, 直接在 lambda 里将当前的 continuation 绑定到 co_cont 上, 这样用户 create 的时候传入的函数就只需要调用 yield 了

可惜除了 vsc 都没有 Ice 的高亮(

最新文章

  1. C和指针 第十七章 经典数据类型 堆栈 队列 二叉树
  2. JS操作未跨域iframe里的DOM
  3. 大气漂亮的jQuery水晶样式下拉菜单
  4. git命令的使用 【备用】
  5. vs 2015 写php太爽了,毕竟我接触的第一款ide就是vs啊
  6. 使用photoshop,把图片背景变成透明
  7. 从内存溢出看Java 环境中的内存结构(转)
  8. H5与Android之间的交互
  9. rtems的GNU(GCC)编译环境配置
  10. SSM框架开发web项目系列(二) MyBatis真正的力量
  11. jQuery:deferred [转]
  12. js,jq.事件代理(事件委托)复习。
  13. ●BZOJ 4453 cys就是要拿英魂!
  14. 菜鸟玩云计算之十四:克隆虚拟机及ssh登录的问题
  15. 006-CSS引入外部字体
  16. pyinstaller
  17. JAVA如何request没有参数的post提交
  18. Maven 标签
  19. Android-Drawable(三)
  20. A Tool To Plot Mathematical Function

热门文章

  1. Centos7 selinux关闭
  2. 学习笔记--我的第一个Java程序
  3. 利用栈实现括号匹配(python语言)
  4. MySQL数据库学习打卡 DAY2
  5. 【记录一个问题】golangci-lint.exe中,盘符大写就会执行出错
  6. Floodlight+Mininet的SDN实验平台搭建初探
  7. pytest文档4-fixture之conftest.py
  8. Android开发之事件
  9. 返回值String表示视图
  10. 删除修改docker网络环境