How about something like this
struct Atom
name::String
molecule::Int
end
atoms = [ Atom("O",1), Atom("H",1), Atom("H",1),
Atom("O",2), Atom("H",2), Atom("H",2) ]
struct EachMolecule
atoms::Vector{Atom}
end
eachmolecule(atoms) = EachMolecule(atoms)
function Base.iterate(em::EachMolecule, state = 1)
r0 = state
r0 > length(em.atoms) && return nothing
m0 = em.atoms[r0].molecule
r1 = r0
while r1 <= length(em.atoms)
em.atoms[r1].molecule != m0 && return (r0:r1 - 1, r1)
r1 += 1
end
return (r0:r1 - 1, r1)
end
julia> for molecule in eachmolecule(atoms)
println(molecule)
end
1:3
4:6