1

Usually all R's objects are immutable with copy-on-modify semantics. This is not true for environments, which have reference semantics. Iterators in R (iterators package) are implemented using environments and are mutable. This can be confusing. Consider following simple example:

library(iterators)
it1 <- iter(1:4)
it2 <- it1

nextElem(it1)
# 1
nextElem(it2)
# 2

And this is not what most of R users expect. The question is how to effectively make a copy of iterator? For the moment I have messy solution (borrowed this idea) for simple case above:

it1 <- iter(1:4)
it2 <- it1
it2$state  <- as.environment(as.list(it1$state))
next_el(it1)
# 1
next_el(it2)
# 1

But I feel like I'm missing something, and it also doesn't look like general solution.

Community
  • 1
  • 1
Dmitriy Selivanov
  • 4,545
  • 1
  • 22
  • 38
  • Simple answer: Don't make a copy of an iterator. If you still need that, you could wrap your code into a function and call it `copy`. – Roland Mar 14 '16 at 15:52
  • This question raised from here [#65](https://github.com/dselivanov/text2vec/issues/65) and [#71](https://github.com/dselivanov/text2vec/issues/71). Users confused by such behaviour. And I personally also don't like that. – Dmitriy Selivanov Mar 14 '16 at 16:00
  • 1
    Well, I suggest to follow the example of the data.table devs and provide a `copy` function. That could be what you use above or you could probably write a C function that copies an environment. Or if you don't mind another dependence, you could use `restorepoint::clone.environment`. – Roland Mar 14 '16 at 16:12

1 Answers1

0

I ended with reimplementation of iterators on top of R6 (thanks to @hadley's suggestion on twitter). R6 includes handy clone method with deep = c(TRUE, FALSE) option. Someone interested can find examples here.

Dmitriy Selivanov
  • 4,545
  • 1
  • 22
  • 38