# Custom Iterators and Last Value

**URL:** <https://discourse.julialang.org/t/custom-iterators-and-last-value/16291>\
**Category:** General Usage\
**Created:** [October 13, 2018, 7:39pm UTC](https://discourse.julialang.org/t/custom-iterators-and-last-value/16291 "2018-10-13T19:39:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![gideonsimpson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gideonsimpson/32/1928_2.png) [@gideonsimpson](https://discourse.julialang.org/u/gideonsimpson)\
**Post date:** [October 13, 2018, 7:39pm UTC](https://discourse.julialang.org/t/custom-iterators-and-last-value/16291/1 "2018-10-13T19:39:16Z")

</div>

I’m trying to write an iterator for a custom data structure with the following as a test code:

```julia
struct DataStruct{TF<:AbstractFloat, TI<:Integer}
   X::Vector{TF}
   Y::Vector{TI}
end

function Base.length(D::DataStruct)
   return length(D.X)
end

function Base.eltype(D::DataStruct)
   return typeof((D.X[1], D.Y[1]))
end

function Base.iterate(D::DataStruct, state = ((D.X[1], D.Y[1]), 1))
   element, count = state
   if count >= length(D)
      return nothing
   end
   return (element, ((D.X[count+1], D.Y[count+1]), count+1))
end

n = 11;
D = DataStruct{Float64, Int}(range(0,stop=1, length=n), 2*ones(n));
for Z in D
   println(Z)
end

```

This code, obviously, misses the last element in the structure `D`, and I’m trying to understand the ‘‘proper’’ way to handle this.

Alternatively, would I just be better off doing?

```julia
for Z in zip(D.X,D.Y)
    println(Z)
end

```

---

<div class="post-metadata">

**Author:** ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)\
**Post date:** [October 13, 2018, 8:07pm UTC](https://discourse.julialang.org/t/custom-iterators-and-last-value/16291/2 "2018-10-13T20:07:38Z")

</div>

```julia
if count > length(D)
    return nothing

```

---

<div class="post-metadata">

**Author:** ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)\
**Post date:** [October 13, 2018, 8:10pm UTC](https://discourse.julialang.org/t/custom-iterators-and-last-value/16291/3 "2018-10-13T20:10:33Z")

</div>

You use a very nonstandard pattern in your iterator. Why keeping the element in the state? Start the state at 1 and increment it every call to iterate, stop when state is greater than the length of the arrays

```julia
function Base.iterate(D::DataStruct, state = 1)
   
   if state > length(D)
      return nothing
   end
   return (D.X[state], D.Y[state]), state+1
end``
```
