递归整型列表的简单实现(Kotlin)

/**
 * Created by FangJu on 2020/1/30
 */
sealed class IntList {
    object Nil : IntList() {
        override fun toString(): String {
            return "Nil"
        }
    }

    data class Cons(val head: Int, val tail: IntList) : IntList() {
        override fun toString(): String {
            return "$head, ${tail.toString()}"
        }
    }

    fun joinToString(sep: Char): String {
        return when (this) {
            Nil -> "Nil"
            is Cons -> {
                "$head$sep${tail.joinToString(sep)}"
            }
        }
    }
}

operator fun IntList.component1(): Int? {
    return when (this) {
        IntList.Nil -> null
        is IntList.Cons -> head
    }
}

operator fun IntList.component2(): Int? {
    return when (this) {
        IntList.Nil -> null
        is IntList.Cons -> tail.component1()
    }
}

operator fun IntList.component3(): Int? {
    return when (this) {
        IntList.Nil -> null
        is IntList.Cons -> tail.component2()
    }
}

fun IntList.sum(): Int {
    return when (this) {
        IntList.Nil -> 0
        is IntList.Cons -> {
            1 + tail.sum()
        }
    }
}

fun intListOf(vararg ints: Int): IntList {
    return when (ints.size) {
        0 -> IntList.Nil
        else -> {
            IntList.Cons(ints[0], intListOf(*(ints.slice(1 until ints.size).toIntArray())))
        }
    }
}

fun main() {
    val list = intListOf(0, 1, 2, 3)
    println(list.toString())
    println(list.sum())
    println(list.joinToString('*'))

    println(list.component1())
    println(list.component2())
    println(list.component3())
}
递归整型列表的简单实现(Kotlin)递归整型列表的简单实现(Kotlin) 老头儿ii 发布了112 篇原创文章 · 获赞 19 · 访问量 1万+ 私信 关注
上一篇:mysql 多表及其之间的关系


下一篇:System.console().readPassword()空指针异常