How to make code below to work?
import std/tables
type
Record = object
tags: seq[string]
Db = object
records: seq[Record]
proc stats*(records: iterator(): Record): CountTable[string] =
for record in records():
for tag in record.tags: result.inc tag
echo Db().records.items.stats
How about a template?
import std/tables
type
Record = object
tags: seq[string]
Db = object
records: seq[Record]
template stats*(records: iterable[Record]): CountTable[string] =
var res: CountTable[string]
for record in records:
for tag in record.tags: res.inc tag
res
echo Db().records.items.stats()
If you cannot use templates for some reason, you can try closure iterators:
import std/tables
type
Record = object
tags: seq[string]
Db = object
records: seq[Record]
func closureItems(records: seq[Record]): iterator(): Record {.closure.} =
return iterator(): Record =
for x in records:
yield x
proc stats*(records: iterator(): Record): CountTable[string] =
for record in records():
for tag in record.tags: result.inc tag
echo Db().records.closureItems.stats
But I would expect this to be slower than the template solution.
See also: iterators in the manual. It has an explanation for the problem you described.