其他分享
首页 > 其他分享> > 递归整型列表的简单实现(Kotlin)

递归整型列表的简单实现(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())
}
老头儿ii 发布了112 篇原创文章 · 获赞 19 · 访问量 1万+ 私信 关注

标签:Cons,return,Nil,递归,Kotlin,list,fun,整型,IntList
来源: https://blog.csdn.net/qq_40833790/article/details/104113403