lazy-evaluation - 在 Crystal 中实现惰性枚举器

标签 lazy-evaluation crystal-lang enumerator

在 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 中那样做,但这是一项正在进行的工作(我希望它还没有被放弃,它似乎在半年前就停滞了)。参见 this issuethis pull request了解更多信息。

关于lazy-evaluation - 在 Crystal 中实现惰性枚举器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54132629/

相关文章:

haskell - 乘以零时的惰性求值

scala - 了解 Stream scala 交错转换行为

正则表达式惰性量词断言开始和结束

Java循环退出条件

Ruby:环回枚举器

nhibernate - 强制为一个实例加载所有 nhibernate 代理

dependencies - 如何生成没有依赖项的 Crystal 可执行文件?

白手起家

dart - 为什么Dart无法从Crystal解码base64?

c++ - 使用 cin 获取类的枚举类型