纯函数式编程:如何将元素添加到列表中? [英] pure functional programming: how to add an element to a list?

查看:96
本文介绍了纯函数式编程:如何将元素添加到列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在纯函数式编程中,我们不修改任何函数的参数。那么,我们如何设计一个函数来为其参数添加一个元素,一个列表?例如,函数列表添加(elem,list)。此问题与此主题类似:功能性编程:状态与重新分配



我的解决方案是深层复制输入列表,然后使用一些破坏性操作,如 append 来操纵新的。我是正确的吗?

追加

我从图表-copy算法:

  //在节点
中public节点deepCopy(Map< Node,Node> isomorphism){
节点拷贝= isomorphism.get(this);
if(copy == null){
copy = new Node();
isomorphism.put(this,copy);
for(Node connection:connections){
copy.connections.add(connection.deepCopy(isomorphism));
}
}
返回副本;
}

要深度复制图形,必须跟踪每个正在复制的节点。在宇宙中,我们使用同构参数来做到这一点。我认为使这个 deepCopy 操作的纯函数版本的唯一方法是不仅返回变量 copy ,而且还有一个标志,指示返回的节点是否是新节点。对吗?

解决方案

是的,您必须返回一个添加元素的新列表。



但是,这不需要深层复制。功能性语言通常具有持久性数据结构,可以让部分结构在各个版本之间共享,因此你可以例如在O(1)时间前添加一个元素到列表中。


In pure functional programming, we do not modify any arguments of a function. Then, how can we design a function that adds an element to its argument, a list? For example, function list add (elem, list). This question is similar to this thread: Functional programming: state vs. reassignment .

My guess solution is to deep-copy the input list and then to use some destructive operations like append to manipulate the new one. Am I right?

appending

I copy the following code from a graph-copy algorithm:

// in Node
public Node deepCopy(Map<Node, Node> isomorphism) {
    Node copy = isomorphism.get(this);
    if (copy == null) {
        copy = new Node();
        isomorphism.put(this, copy);
        for (Node connection: connections) {
            copy.connections.add(connection.deepCopy(isomorphism));
        }
    }
    return copy;
}

To deep-copy a graph, one must track every node that is being copied. In the universe, we use the isomorphism argument to do that. I think the only way to make a pure functional version of this deepCopy operation is to return not only the variable copy but also a flag indicating whether the returned node is new one. Right?

解决方案

Yes, you have to return a new list with the element added.

However, this doesn't have to require a deep copy. Functional languages typically feature persistent data structures which allow parts of the structure to be shared between versions, so that you can e.g. prepend an element to a list in O(1) time.

这篇关于纯函数式编程:如何将元素添加到列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆