如何在Julia中实现迭代器? [英] How to implement an iterator in Julia?

查看:79
本文介绍了如何在Julia中实现迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Julia中实现一个迭代器,但是当for循环已尝试调用start时会出现异常.

I am trying to implement an iterator in Julia, but get an exception when the for-loop tries to call start already.

这就是我得到的(我先运行include(...),然后运行using RDF):

Here is what I get (I ran include(...), then using RDF):

julia> methods(start)
# 1 method for generic function "start":
start(graph::Graph) at /Users/jbaran/src/RDF.jl/src/RDF.jl:214

julia> for x in g
       println(x)
       end
ERROR: `start` has no method matching start(::Graph)
 in anonymous at no file

RDF模块中的函数定义目前如下所示:

The function definition in the RDF module looks like this at the moment:

function start(graph::Graph)
    return GraphIterator(collect(keys(graph.statements)), nothing, nothing, nothing, [], [])
end

知道我在做什么错吗?

推荐答案

不要忘记指定Base.-您正在向现有函数添加方法.

Don't forget to specify Base. - you are adding methods to an existing function.

module MyMod
  type Blah
    data
  end
  export Blah
  Base.start(b::Blah) = 1
  Base.done(b::Blah,state) = length(b.data) == state-1
  Base.next(b::Blah,state) = b.data[state], state+1
end
using MyMod
x = Blah([1,2,3])
for i in x
  println(i)
end

这从Julia 0.3开始生效.

This works as of Julia 0.3.

这篇关于如何在Julia中实现迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆