Iterator Wrappers
An iterator wrapper, iter
, can wrap any iterator to automatically add support for a set of chainable, lazily-evaluated utility methods.
-
$iter(arg: iterator|iterable) -> iter
-
Wraps an iterator in an
iter
wrapper. The argument can be an iterator or an instance of an iterable type.
Iterators returned by Pyro builtins come pre-wrapped in iter
wrappers, e.g. the character iterator returned by a string's :chars()
method:
for char in "abcd":chars():enum() { echo char; }
The :enum()
method is provided by the iter
wrapper.
It adds an index to each element in the input, giving us the following output:
(0, 'a') (1, 'b') (2, 'c') (3, 'd')
Iterator wrappers have the following methods:
-
:count() -> i64
-
Returns the number of items in the sequence. Note that calling this method exhausts the iterator.
-
:enum() -> iter[tup[i64, any]]
:enum(start_index: i64) -> iter[tup[i64, any]]
-
Adds an enumeration wrapper to an iterator. Output values are two-item tuples containing an integer index and the original input value.
start_index
defaults to zero if not specified. -
:filter(callback: func(any) -> bool) -> iter
-
Returns a new
iter
instance that filters the output of the source iterator using thecallback
function.callback
should be a callable that takes a single argument and returns abool
; input values will be passed through the filter ifcallback
returnstrue
. -
:join(sep: str) -> str
-
Joins the items returned by the iterator into a string, with each pair of items separated by
sep
. Items are automatically stringified — this is equivalent to calling$str()
on each item.Returns an empty string if the iterator is empty or exhausted.
-
:map(callback: func(any) -> any) -> iter
-
Returns a new
iter
instance mapping the functioncallback
to the output of the source iterator.callback
should be a callable that takes a single argument; its return values will form the output of the new iterator. -
:skip_first(n: i64) -> iter
-
Skips the first
n
items generated by the iterator. Panics if the iterator generates less thann
items. -
:skip_last(n: i64) -> iter
-
Skips the last
n
items generated by the iterator. Panics if the iterator generates less thann
items.Note that this method needs to buffer the iterator's full output to determine the end point.
-
:to_set() -> set
-
Drains the iterator into a new set.
-
:to_vec() -> vec
-
Drains the iterator into a new vector.