LoginSignup
1
0

More than 3 years have passed since last update.

はじめに

タイトルの通りです。

repeat

fun <T> repeat(count: Int, input: T): List<T> {
    val list = mutableListOf<T>()
    for (i in 0 until count) {
        list.add(input)
    }
    return list.toList()
}

repeat(3, 3)

出力
(3,3,3)

range

fun range(a: Int, b: Int): List<Int> = (a..b).toList()

range(1, 3)

出力
(1,2,3)

append

fun <T> List<T>.append(list: List<T>): List<T> {
    val acc = this.toMutableList()
    acc.addAll(list)
    return acc
}

listOf(1, 2, 3).append(listOf(4, 5))

出力
(1,2,3,4,5)

concat

fun <T> List<List<T>>.concat(): List<T> {
    return this.fold(mutableListOf()) { acc, list ->
        acc.addAll(list)
        acc
    }
}

listOf(listOf(1,2,3), listOf(4,5,6), listOf(7,8,9)).concat()

出力
(1,2,3,4,5,6,7,8,9)

head

fun <T> List<T>.head(): T {
    return this[0]
}

listOf(1, 2, 3).head()

出力
1

tail

fun <T> List<T>.tail(): T {
    return this[this.size - 1]
}

listOf(1, 2, 3).tail()

出力
3
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0