Say I want to modify a number or some other primitive inside of a function. For example, something like this (note: pseudocode):
// apply fn to every value in a tree, in-order traversal
function treeReduce (tree, fn, result):
if (tree == undefined) return
treeReduce(tree.left, fn, result)
result = fn(result, tree.value)
treeReduce(tree.right, fn, result)
sum = 0
treeReduce(myTree, +, sum)
obviously this won't work, because result
is just being reassigned, and the sum
passed in won't see the modifications. So a common way I have gotten around this (in any pass-by-value language like Python or Javascript) is using wrappers:
// apply fn to every value in a tree, in-order traversal
function treeReduce (tree, fn, result):
if (tree == undefined) return
treeReduce(tree.left, fn, result)
result[0] = fn(result[0], tree.value)
treeReduce(tree.right, fn, result)
sumWrapper = [0]
treeReduce(myTree, +, sumWrapper)
However, I recently searched the internet to see if this is a common pattern, and can't find much information about it. Specifically, I'd like to know three things:
- is this a common pattern?
- is this good practice?
- if not, any alternatives?