1
\$\begingroup\$

I have a need to drop quantities of elements from an iterator beyond Int.MaxValue so I wrote a helper function that does just that. However, I can't help but feel like I'm doing this the dumb way - that there's got to be some built-in language construct or at least a more elegant way of tackling the problem.

/**
 * drops a Long's worth of elements from an Iterator[T] and returns the succeeding element.
 * 
 * @param dropVal is the number of elements we want to drop
 * @param iteratorLong is the the iterator from which you want to drop lots-o-elements
 * 
 * @return the value you need 
 */
def dropLongAndGet[T](dropVal: Long, iteratorLong: Iterator[T]): T = {    
    val dropCount = dropVal / Int.MaxValue
    val dropCountRemainder = (dropVal % Int.MaxValue).toInt

    var localIteratorReference = iteratorLong
    for (i <- 0L until dropCount) {
        localIteratorReference = iteratorLong.drop(Int.MaxValue)
    }

    return localIteratorReference.drop(dropCountRemainder)
                                 .next     
}

Also, I am aware that the code will work w/o the return keyword - I use it because I'm used to seeing it from Java, it doesn't hurt anything to have it there, and I think it helps non-Scala programmers make sense of what's going on if/when they have to read my code.

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

You can use a (tail-)recursive method to achieve same result:

def drop[T](c: Long, i: Iterator[T]): Iterator[T] = {
  if (c > Int.MaxValue) drop(c - Int.MaxValue, i.drop(Int.MaxValue))
  else i.drop(c.toInt)
}

def dropLongAndGet[T](dropVal: Long, iteratorLong: Iterator[T]): T = {
  drop(dropVal, iteratorLong).next
}
\$\endgroup\$
2
  • \$\begingroup\$ ooohh nice -- that is more elegant! \$\endgroup\$
    – snerd
    Commented Dec 15, 2016 at 21:19
  • \$\begingroup\$ You could add the @tailrec annotation todrop for compiler-guaranteed tail recursion. \$\endgroup\$ Commented Dec 25, 2016 at 7:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.