R/ihasNext.R

Defines functions hasNext.ihasNext ihasNext

Documented in hasNext.ihasNext ihasNext

# This is based on code that was contributed by Hadley Wickham

hasNext.ihasNext <- function(obj, ...) {
  obj$hasNext()
}

ihasNext <- function(iterable) {
  it <- iter(iterable)

  if (inherits(it, 'ihasNext')) {
    it
  } else {
    cache <- NULL
    hasnext <- NA

    nextEl <- function() {
      if (! hasNx()) {
        stop('StopIteration', call.=FALSE)
      }

      hasnext <<- NA
      cache
    }

    hasNx <- function() {
      if (is.na(hasnext)) {
        tryCatch({
          cache <<- nextElem(it)
          hasnext <<- TRUE
        },
        error=function(e) {
          if (identical(conditionMessage(e), 'StopIteration')) {
            hasnext <<- FALSE
          } else {
            stop(e)
          }
        })
      }

      hasnext
    }

    obj <- list(nextElem=nextEl, hasNext=hasNx)
    class(obj) <- c('ihasNext', 'abstractiter', 'iter')
    obj
  }
}

Try the itertools package in your browser

Any scripts or data that you put into this service are public.

itertools documentation built on May 2, 2019, 6:16 p.m.