首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数编程,密封类列表

函数编程,密封类列表
EN

Stack Overflow用户
提问于 2019-11-27 19:20:42
回答 1查看 162关注 0票数 0

我正在用一个密封的类列表和一个映射函数来练习一些函数式编程。

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

代码语言:javascript
复制
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
    }

}

映射函数内密封类工作正常,但现在我希望它在外部运行--密封类类似

代码语言:javascript
复制
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))
    }
}

但是现在“头”和“尾”不再起作用了,因为没有得到解决的参考资料。我尝试过不同的策略,但什么都没用。有什么办法解决吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-11 14:41:52

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59077164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档