官术网_书友最值得收藏!

Getting ready

The basic variant of the generateSequence() function is declared as follows:

fun <T : Any> generateSequence(nextFunction: () -> T?): Sequence<T>

It takes one parameter called nextFunction, which is a function that returns the next elements of the sequence. Under the hood, it is being invoked by the Iterator.next() function, inside the Sequence class' internal implementation, and allows instantiation of the next object to be returned while consuming the sequence values.

In the following example, we are going to implement a finite sequence that emits integers from 10 to 0:

var counter = 10
val sequence: Sequence<Int> = generateSequence {
counter--.takeIf { value: Int -> value >= 0 }
}
print(sequence.toList())

The takeIf() function applied to the current counter value checks whether its value is greater or equal to 0. If the condition is fulfilled, it returns the counter value; otherwise, it returns null. Whenever null is returned by the generateSequence() function, the sequence stops. After the takeIf function returns the value, the counter value is post-decremented. The preceding code will result in the following numbers being printed to the console:

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

The subsequent values of the Fibonacci sequence are generated by summing up their two preceding ones. Additionally, the two first values are equal to 0 and 1. In order to implement such a sequence, we are going to use an extended variant of the generateSequence() function with an additional seed parameter, declared as follows:

fun <T : Any> generateSequence(seed: T?, nextFunction: (T) -> T?): Sequence<T>
主站蜘蛛池模板: 浦北县| 镇雄县| 阿鲁科尔沁旗| 宜昌市| 鹤岗市| 甘肃省| 克东县| 全南县| 莒南县| 曲阜市| 广平县| 盘锦市| 甘南县| 永胜县| 师宗县| 布拖县| 景洪市| 阳西县| 蓝山县| 武城县| 清苑县| 宜章县| 桐城市| 武强县| 富源县| 马鞍山市| 永安市| 高邑县| 河池市| 手游| 新竹市| 富平县| 偏关县| 城固县| 濮阳县| 博爱县| 荃湾区| 沈阳市| 伊宁市| 集贤县| 济宁市|