added a helper method for converting functions into iterators (which have all the various standard library APIs on them)
This commit is contained in:
@@ -1,6 +1,7 @@
|
|||||||
package kotlin
|
package kotlin
|
||||||
|
|
||||||
import kotlin.support.AbstractIterator
|
import kotlin.support.AbstractIterator
|
||||||
|
import kotlin.support.FunctionIterator
|
||||||
|
|
||||||
import java.util.*
|
import java.util.*
|
||||||
import java.util.Iterator
|
import java.util.Iterator
|
||||||
@@ -77,3 +78,8 @@ inline fun <T, R> java.util.Iterator<T>.flatMap(transform: (T)-> java.util.Itera
|
|||||||
return flatMapTo<>(ArrayList<R>(), transform)
|
return flatMapTo<>(ArrayList<R>(), transform)
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns an iterator which invokes the function to calculate the next value on each iteration until the function returns null
|
||||||
|
*/
|
||||||
|
inline fun <T> iterate(nextFunction: () -> T?) : Iterator<T> = FunctionIterator(nextFunction)
|
||||||
@@ -70,4 +70,19 @@ abstract class AbstractIterator<T>: java.util.Iterator<T> {
|
|||||||
protected fun done() {
|
protected fun done() {
|
||||||
state = State.Done
|
state = State.Done
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An [[Iterator]] implementation which invokes a function to calculate the next value in the iteration
|
||||||
|
* until the function returns null
|
||||||
|
*/
|
||||||
|
class FunctionIterator<T>(val nextFn: () -> T?) : AbstractIterator<T>() {
|
||||||
|
|
||||||
|
override fun computeNext(): T? {
|
||||||
|
val next = (nextFn)()
|
||||||
|
if (next == null) {
|
||||||
|
done()
|
||||||
|
}
|
||||||
|
return next
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package iterators
|
||||||
|
|
||||||
|
import kotlin.*
|
||||||
|
import kotlin.test.*
|
||||||
|
import kotlin.util.*
|
||||||
|
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class FunctionIteratorTest {
|
||||||
|
|
||||||
|
Test fun iterateOverFunction() {
|
||||||
|
var count = 3
|
||||||
|
|
||||||
|
val iter = iterate<Int> {
|
||||||
|
count--
|
||||||
|
if (count >= 0) count else null
|
||||||
|
}
|
||||||
|
|
||||||
|
val list = iter.toList()
|
||||||
|
assertEquals(arrayList(2, 1, 0), list)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user