Rで、自分でイテレータを定義する時の注意点
次のコードは、値x
をtimes
回繰り返すイテレータです。 問題なく動きます。
library(iterators)
library(foreach)
f <- function(x, times) {
nextEl <- function() {
if (times > 0) {
times <<- times - 1
} else {
stop("StopIteration")
}
x
}
obj <- list(nextElem=nextEl)
class(obj) <- c("abstractiter", "iter")
obj
}
foreach(i = f(3, 4)) %do% i
## [[1]]
## [1] 3
##
## [[2]]
## [1] 3
##
## [[3]]
## [1] 3
##
## [[4]]
## [1] 3
次のコードは、同じに見えるようで、エラーを出します。コピペしてみてください。
何がいけないのでしょうか。
f <- function(x, times) {
nextEl <- function() {
if (times > 0) {
times <<- times - 1
} else {
stop("stopIteration")
}
x
}
obj <- list(nextElem=nextEl)
class(obj) <- c("abstractiter", "iter")
obj
}
foreach(i = f(3, 4)) %do% i
## Error in i : stopIteration
↓答え(選択すると文字が出ます)
"stopIteration"の最初の文字が小文字
ちなみに、as.list
でも同じエラーが出るので、foreach
ではなくiterators
の仕様と解釈しています。
以下、環境情報
sessionInfo()
## R version 3.4.0 (2017-04-21)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 14.04.5 LTS
##
## Matrix products: default
## BLAS: /usr/lib/openblas-base/libopenblas.so.0
## LAPACK: /usr/lib/lapack/liblapack.so.3.0
##
## locale:
## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
## [7] LC_PAPER=en_US.UTF-8 LC_NAME=C
## [9] LC_ADDRESS=C LC_TELEPHONE=C
## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] foreach_1.4.3 iterators_1.0.8
##
## loaded via a namespace (and not attached):
## [1] compiler_3.4.0 backports_1.0.5 magrittr_1.5 rprojroot_1.2
## [5] tools_3.4.0 htmltools_0.3.6 yaml_2.1.14 Rcpp_0.12.10
## [9] codetools_0.2-15 stringi_1.1.5 rmarkdown_1.5 knitr_1.15.1
## [13] stringr_1.2.0 digest_0.6.12 evaluate_0.10