我终于把链表迭代器做好了

对于代码

for i in list
    #code 
end

可以解释为

next = iterate(iter)

while next !== nothing

(i, state) = next

# body

next = iterate(iter, state)

end

其中要注意的是iterator方法有两个
于是这样定义第一个方法

Base.iterator(list::List{T}) where T = list.size==0 ? nothing : (list.head,list.head)

第二个方法

Base.iterator(list::List{T},state) where T =
   begin
        state.next==nothing ? nothing : (state.next,state.next)
   end

需要注意的是state第一次被赋值是在 (i, state) = next 这里,state的值会被当作参数被下一个iterator(list,state) 调用

这里显示调试结果

出现了点问题,先写下

l=List{Int}()
for i in 1:10
    push(l,i)
end
这是调试函数
@time for i in l
    print(i.value," ")
   end 

第一次调用调试函数显示的结果 : 1 2 3 4 5 6 7 8 9 10 0.027430 seconds (29.82 k allocations:1.423MiB)
第二次调用调试函数显示的结果: 1 2 3 4 5 6 7 8 9 10 0.000069 seconds (61 allocations: 2.266KiB)
需要强调在repl中调试和脚本环境中调试结果也差不多
怎么两次结果差了这么多

第一次调用函数需要编译,用 BenchmarkTools 包里的 @btime 可以去除编译时间的影响,并且也会多次测量。

具体怎么操作呢:thinking:

打开 Julia REPL,然后:

julia> # 输入 ] 进入 Pkg 模式

pkg> add BenchmarkTools # 添加包

pkg> # 输入 backspace 返回默认模式

julia> using BenchmarkTools

julia> @btime for i in l
           print(i.value," ")
       end