3 ms·
The allocation strategy used is only a tangential problem. The purpose of the example is to demonstrate the functionality of the library in brief, not to walk t
by boomlinde 6y ago
The allocation strategy used is only a tangential problem. The purpose of the example is to demonstrate the functionality of the library in brief, not to walk the reader through problems that C programmers face in general.
I would suggest recursively walking through the original tree, creating an equivalent tree in the process instead of copying the original elements.
- syockit 6y agoYeah, I suppose. /* get size required for malloc */ size_t getsize(const BinaryTree *tree) { size_t acc = sizeof(*tree); match(*tree) { of(Leaf, x) { return acc; } of(Node, lhs, x, rhs) { return getsize(*lhs) + acc + getsize(*rhs); } } } BinaryTree* copy(BinaryTree *dest, const BinaryTree *src) { dest->tag = src->tag; match(*src) { of(Leaf, x) { *dest = Leaf(*x); } of(Node, lx, x, rx) { match(*dest) { of(Node, ly, y, ry) { *ly = dest + 1; *ry = copy(*ly, *lx); *y = *x; copy(*ry, *rx); } otherwise {} } } } return dest + 1; } Kind of hackish, but I guess it works.
- klodolph 6y agoHackish????