fun Collection.asCyclingSequence(): Sequence = Sequence { this.asIterable().cyclingIterator() } fun Iterable.cyclingIterator(): Iterator { return object: Iterator { var iter = this@cyclingIterator.iterator() override fun hasNext(): Boolean { if (!iter.hasNext()) { iter = this@cyclingIterator.iterator() } return iter.hasNext() } override fun next(): T { if (!hasNext()) { throw NoSuchElementException("Can't cycle through an empty iterator") } return iter.next() } } }