首页 > 解决方案 > 在 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模仿这种东西的惯用方式是什么?

标签: lazy-evaluationcrystal-langenumerator

解决方案


有点啰嗦...看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 完全一样的方法,但这是一项正在进行的工作(我希望它还没有被放弃,它似乎在半年前就停滞了)。有关更多信息,请参阅此问题此拉取请求


推荐阅读