【问题标题】:Kotlin: functional programming, sealed class ListKotlin:函数式编程,密封类 List
【发布时间】:2019-11-27 19:20:42
【问题描述】:

我正在使用密封类 List 和 map 函数练习一些函数式编程。

到目前为止,密封类的代码

sealed class List <T> {

    class Node <T> ( val head : T , val tail : List<T>) : List<T> () {
        override fun toString () =
            "${head.toString()} , ${tail.toString()}"
    }

    object Nil : List<Nothing> ()  {
        override fun toString () = "NIL"
    }

    companion object {
        operator
        fun <T> invoke (vararg values : T ) : List<T>{
            val empty = Nil as List<T>
            val res = values.foldRight( empty , { v, l -> l.addFirst(v)   })
            return res
        }
    }

    fun addFirst ( head : T ) : List<T> = Node (head , this)

    fun removeFirst ()  : List <T> = when (this) {
        is Nil -> throw IllegalStateException()
        is Node<T> -> this.tail
    }

}

map 函数 inside 密封类工作正常,但现在我希望它在 outside 运行像密封类

fun <T,R> map (list:List<T>, f: (T) -> R) {
    when(list) {
        is List.Nil -> List.Nil as List<R>
        is List.Node -> List.Node<R> (f(head), tail.map(f))
    }
}

但现在“head”和“tail”不再起作用,因为未解析的引用。我尝试了不同的策略,但没有任何效果。任何想法如何解决它?

【问题讨论】:

  • list.head, list.tail?
  • 这是我的第一选择。但是 : is List.Node -> List.Node (f (list.head), list.tail.map (f)) 映射不再起作用
  • 经过更多研究乐趣找到了解决方案 List.map (f : (T) -> R) : List = when (this) { List. Nil -> List.Nil as List is List.Node -> List.Node (f(head), tail.map(f)) }

标签: kotlin functional-programming sealed-class


【解决方案1】:

在更多的研究之后找到了一个解决方案 fun List.map (f : (T) -> R) : List = when (this) { List.Nil -> List.Nil as List is List.Node -> List.节点 (f(head), tail.map(f)) }

【讨论】:

    猜你喜欢
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    相关资源
    最近更新 更多