Tokay v0.6.1 is a "small milestone" towards Tokay v0.7 and was released now. It allows for chained comparisons and established iterators, including a new for...in
-syntax.
Chained comparisons
With this release, Tokay now support for chained comparisons, like
2 == 2 == 2 # true
which leads to true
.
Previously, this expression turned into (2 == 2) == 2
wich turned into true == 2
, which turned into false
.
It works with any comparions chains of arbitrary length and operators, as code is constructed alongside. The last item of an expression will always be compared. This looses the previously supported static evaluation feature for comparisons, but makes many things feel more natural in expressions.
Iterators
Iterators are objects to sequentially loop over the content of other objects. Tokay v0.6.1 established iterators and the new for...in
-syntax. The previous for
-syntax is not supported anymore.
With Tokay v0.6.0, the only way to iterate over the items of a list l = (1, 2, 3)
is
for i = 0; i < l.len; i++ {
print(i)
}
In Tokay v0.6.1, this is now turned into
for i in l {
print(i)
}
Iterators can also be made on any object. A str
is a special case, as it offers an indexing method:
list(iter(true)) # (true, )
list(iter(42.5)) # (42.5, )
list(iter("Hello")) # ("H", "e", "l", "l", "o")
In detail, an iterator is an object on its own, which allows to iterate forwards (or backwards) through either the content of another object, or even to produce values in a specific range. Latter is, for example, the case with
for i in range(1, 100, 2) {
print(i)
}
which counts from 1 to 100 in steps of 2. As the 100 is never directly reached, it will stop after printing 99.
Let's use it on dicts:
d = (
first => 1
second => 2
third => 3
)
list(iter(d)) # (1, 2, 3)
list(d.keys) # ("first", "second", "third")
list(d.items) # (("first", 1), ("second", 2), ("third", 3))
Iterators can also be reversed in most cases:
list(d.items().rev) # (("third", 3), ("second", 2), ("first", 1))
The iter API is currently provided as follows:
iter()
creates an iterator from an object, by callingobject.iter()
or automatically a MethodIter on an objectiter.rev()
reverses an iterator, if possibleiter.next()
returns the iterators next elementiter.collect()
collects and iterator into a list; is used bylist()
on aniter
as welliter.enum()
creates an enumerated iteratoriter.map()
creates a mapped/filtered iterator
Iterators are generated by
range()
creates a range counting iterator.iter(obj)
tries to iterator over an object; Returns the object itself as fallback.dict.keys()
returns an iterator over the keys of a dict; useiter(dict)
to get an iterator over the values only.dict.items()
returns an iterator over the key-value-pairs of a dict.
More about iterators and their usage will follow. There might also be improvements soon.