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?