Skip to contents

wrapped <- ihasnext(obj) wraps an iteror object with the ihasNext class. Then hasNext(wrapped) will indicate if the iterator has another element.

Usage

hasNext(obj, ...)

ihasNext(obj, ...)

Arguments

obj

an iterable

...

extra arguments may be passed along to iteror.

Value

Logical value indicating whether the iterator has a next element.

Details

A class ihasNext was introduced in the itertools package to try to reduce the boilerplate around extracting the next value using iterators::nextElem. ihasNext is included in iterors for backward compatibility with iterator code; however, it is less needed when using the nextOr iteration method, as you can directly give an action to take at end of iteration.

Examples

# The bad old style of consuming an iterator in a loop with `nextElem`:
  it <- ihasNext(iteror(c('a', 'b', 'c')))
  tryCatch(repeat {
    print(iterators::nextElem(it))
  }, error=function(err) {
    if (conditionMessage(err) != "StopIteration")
      stop(err)
  })
#> [1] "a"
#> [1] "b"
#> [1] "c"

# with ihasNext, this became:
  it <- ihasNext(iteror(c('a', 'b', 'c')))
  while (hasNext(it))
    print(iterators::nextElem(it))
#> [1] "a"
#> [1] "b"
#> [1] "c"

# But using `nextOr` all you need is:
  iteror(c('a', 'b', 'c'))
#> function (or) 
#> {
#>     if (i >= count) {
#>         or
#>     }
#>     else {
#>         i <<- i + 1
#>         obj[[i]]
#>     }
#> }
#> <bytecode: 0x563197266328>
#> <environment: 0x56319607a9b0>
#> attr(,"class")
#> [1] "iteror" "iter"  
  repeat print(nextOr(it, break))