Is it possible to implement [] as an iterator? Right now I have proc [] operator implementation for slice that builds seq[T] (allocation), but I often use it as for sub in node[1..n], so there is no real use to build an intermediate sequence. I tried
type Custom = distinct string
iterator `[]`(a: Custom, r: HSlice[int, int]): char =
for q in r:
yield a.string[q]
for val in Custom("test")[2..3]:
echo val
but it fails with compilation error
Error: type mismatch: got <prog.Custom, HSlice[system.int, system.int]>
but expected one of:
iterator `[]`(a: Custom; r: HSlice[int, int]): char
first type mismatch at position: 0
proc `[]`(s: string; i: BackwardsIndex): char
first type mismatch at position: 0
First overload seems to fit perfectly (a: Custom; r: HSlice[int, int]), but compilation still fails. If I use [] explicitly ([](1, 2 .. 3)) it works, but that looks quite bad.
It is possible to use regular operators as iterators - system.nim defines iterator .. (https://nim-lang.org/docs/system.html#...i%2CT%2CT)
In my real use case I have to collect subnodes into sequence using calls to C procedure, so I have to either build full sequence, or provide an iterator. Sequence solution also performs worse for code like
for sub in node[0 .. ^1]:
if sub.matches(< ... some predicate ... >):
# do things
break
I have to pay for the whole sequence, while I might actually need only first couple of elements.
Try this https://play.nim-lang.org/#ix=3sXE.
It uses a closure iterator. My guess is that the main issue is that the semantics of [] putting everything but the first parameter on the inside is expected to be inside the brackets isn't implemented for iterators