By co-recursion I mean unfolding a tree, such as with anamorphism from Ed Kmett's recursion-schemes
By re-combining trees I mean graphs that share structure. For example, a binomial option pricing tree, or Pascal's triangle. Both of these have some symmetry, so for efficiency, we would like to avoid re-calculating part of the tree, instead re-using the already-calculated branches.
n.b. this question is not about some clever way to calculate the values in aforementioned examples; it's a general question about recursion.
For example, for options pricing, the tree can be generated like so:
data Tree x = Leaf x | Branch x (Tree x) (Tree x)
ana \(x, depth) ->
if depth == maxDepth
then LeafF x
else BranchF x (p * x, depth + 1) ( (1.0 - p) * x, depth + 1) -- p < 1.0
So the value in an 'up' branch is p * x and the value in a 'down' branch is (1-p) * x. Because of this symmetry, an 'up' followed by a 'down' node will have the same value as a 'down' followed by an 'up' branch. As will it's entire sub-tree.
I think it may be possible to do this passing along State that contains a hashmap of already calculated nodes somehow.
Or if I could somehow access the already-calculated subtree, I could pass it in as a Left in an apomorphism.
Is there some existing morphism that allows this? Or can I code my own?