lazy-evaluation - 在 Crystal 中实现惰性枚举器
问题描述
在 Ruby 中构建一个自定义的惰性枚举器,可以Enumerator
这样使用:
enum = Enumerator.new do |e|
e << value = ".a"
loop { e << value = value.next }
end
enum.next # => ".a"
enum.next # => ".b"
enum.next # => ".c"
enum.rewind
enum.next # => ".a"
Crystal模仿这种东西的惯用方式是什么?
解决方案
有点啰嗦...看Iterator<T>
class DotChar
include Iterator(String)
@current : String = ""
def initialize
@start = ".a"
rewind
end
def next
@current.tap { @current = @current.succ }
end
def rewind
@current = @start
end
end
e = DotChar.new
p e.next # => ".a"
p e.next # => ".b"
p e.next # => ".c"
e.rewind
p e.next # => ".a"
(不能enum
用作标识符,因为那是 Crystal 中的关键字。)
如果你牺牲倒带,你可以做得更简单:
s = ".a"
e = Iterator.of { s.tap { s = s.succ } }
将来可能会有一种与 Ruby 完全一样的方法,但这是一项正在进行的工作(我希望它还没有被放弃,它似乎在半年前就停滞了)。有关更多信息,请参阅此问题和此拉取请求。
推荐阅读
- python - 如何在 SQLAlchemy 中确定自引用一对多关系的方向
- c - 当未一次性发送完整消息时,在套接字上使用 send() 的正确方法是什么?
- jquery - 如何在 Rails 中使用 Jquery Raty 存储来自星级评分的多个值
- android - API 在 POSTMAN 中工作而不是在 Retrofit android 中工作
- firebase - Google Firestore 查找已删除文档的已删除子集合
- python - Qt WebEngine 密码管理器 - 如何检测网站上何时使用用户名/密码
- python - 类型错误:+= 不支持的操作数类型:“标签”和“整数”
- java - 谁能用简单的英语解释对原子性和易失性变量的需求?
- c - 在尝试将元素分配给它时使用带有数组指针的函数有什么问题?
- serverless-framework - 一个资源可以引用另一个资源吗?