There should be a control flow construct in programming languages that can handle tree-like traversal in a nice way, similar to how for/foreach loops can handle linear traversal. It's a bit of a missing gap in the current set of control flow constructs most languages these days have settled on. Its a thing I end up having to do *all the time* and it seems like there should be some shortcuts for it.I posted a thought about this recently and was thinking about how I would want something like that to look like. I can't find anything similar in any other languages. I'm most familiar with C++, so my sample code here is going to be C++-ish, but its general enough that you could fit it into basically anything else. I'm not a language design expert, so this is more of a loose idea than a formal proposal. for_tree(Node* N = mytreeroot; N != NULL; N : {N->left, N->right}){ print(N->value); }with the specifics removed, this is *almost* the same syntax as an existing for loopfor_tree(init; condition; branch){ //body }It's basically a for loop that branches instead of continuing linearly. "init" here runs when you enter the for_tree loop, exactly the same as a normal for loop"condition" must be met to enter the body of the loop"branch" evolves the initial value into multiple branches (it would have to compile down into recursive function calls here)Well, this is significantly easier and less error prone than implementing recursive functions for every operation you'd want to do on every type of tree, plus all the relevant code ends up in-place and readable. This would likely compile down to the same code that a recursive function would anyway. It's just a nice shortcut, the same way for is a nice shortcut for gotos and labels.for_tree(Node* N = mytreeroot; N != NULL; N : {N->left, N->right}){ print(N->value); }would compile down into the equivalent ofvoid for_tree_internal(Node* N){ print(N->value); for(Node* n2 : {N->left, N->right}){ if(n2 != NULL){ for_tree_internal(n2); } } }...
First seen: 2025-04-29 13:23
Last seen: 2025-04-29 19:24