Implement an 'in' operator or something similar
Closed this issue · 3 comments
Currently, we are using the iterators
package, which requires the nextElem
function to be called to get the next element from the iterator. This is annoying.
We should be able to do something like (similar to Python):
for (i in iter(1:3)) {
print(i)
}
... but nope.
Something like %in%
may work. See this SO post.
A complementary, or perhaps, alternative, approach is to implement a feature discussed in the iterators vignette on Writing Custom Iterators.
it <- ihasNext(icount(3))
while (hasNext(it)) {
print(nextElem(it))
}
The hasNext
concept is certainly a reasonable first step to writing general-purpose iterators, but it is not as natural as traversing through a Python iterator
.
For now, the best approach may be to test and to use the foreach package.
Somehow I did not realize that lapply
and sapply
consume iterators in a natural way. This pleases me.
Examples:
# Doubles a sequence
> it <- iseq_len(20)
> sapply(it, function(x) 2*x)
[1] 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40
# Sums the zip'd elements. 1 + 4 + 7, and so on.
> it <- izip(1:3, 4:6, 7:9)
> sapply(it, function(x) sum(unlist(x)))
[1] 12 15 18