From macrakis at alum.mit.edu  Sun Jan 25 22:09:19 2009
From: macrakis at alum.mit.edu (Stavros Macrakis)
Date: Sun, 25 Jan 2009 16:09:19 -0500
Subject: [Rd] Defining an iterator
Message-ID: <8b356f880901251309v7e986f3bl3e734657cf093245@mail.gmail.com>

Inspired by Rudolf Biczok's query of Fri, Jan 23, 2009 at 1:25 AM, I
tried to implement iteration in a generic way using S4. (Though I am
admittedly still struggling with learning S4.)

> setClass("foo",representation(bar="list"))
[1] "foo"
> x<-new("foo",bar=list(1,2,3))

Given this, I would not expect for(i in x)... to work, since R has no
way of knowing that x at bar should be used as is.  What would it do if
the representation included two lists?  What if list(1,2,3) is used by
the class foo to represent something else?

But I did hope that I could put in place some definitions so that the
*class* could define an iterator.

First I tried overloading `for` to allow the definition of iterator
classes, but as a primitive function, `for` cannot be overloaded.

Then I tried to see how the Containers package handles iterators:

> library(Containers);.jinit();.jpackage("Containers")
> ah = MaxHeap(); ah$insert(3)
> for (i in ah) print(i)
[1] NA
> as.list(ah)
[[1]]
[1] NA

Bit it appears that the Containers package's Iterators don't interface
with R's `for` or type conversion system.

So I gave up on iterators, but thought I'd try automatic conversion to lists.

So I defined an automatic conversion from foo to list, since `for`'s
seq argument is specified as "An expression evaluating to a vector
(including a list...)":

    setAs("foo","list",function(from)from at bar)

This and various variants (using "numeric" or "vector" instead of
"list") all give errors.  Is there perhaps some 'sequence' superclass
that I am ignorant of?

I *was* able to overload lapply:

> setMethod("lapply","foo",function(X,FUN,...) lapply(X at bar,FUN,...))
> lapply(x,dput); NULL
1
2
3
NULL

but of course that doesn't affect `for` and other places that expect sequences.

Is there in fact some generic way to handle define iterators or
abstract sequences in R?

          -s



[Rd] Defining an iterator
Stavros Macrakis