And say I want to map a function f at a given level of this tree. For the first level I just do map(f, tree). For the second level I can do map.(f, tree). For the third level I run out of ideas and I am forced to spell it out with a loop. Is there something like a mapat(f, tree, level)?
Thanks @tkf, but I don’t think that is quite what I need. rebroadcast applies f at every level down to n (right?). I want to apply it strictly at level n. But your idea is great. I can do something similar, like
function MagicMapAtLevel(level,func,tree)
if level == 1
return map(func,tree)
else
for subtree in tree
MagicMapAtLevel(level-1,func,subtree)
end
end
end
tree = [[[1,2],[3,4]],[[5,6,7],[8]],[[9,10]]]
println("level 1")
MagicMapAtLevel(1,println,tree)
println("level 2")
MagicMapAtLevel(2,println,tree)
println("level 3")
MagicMapAtLevel(3,println,tree)
If you don’t need the level information you can omit level as parameter. For instance when using arrays with Int64 as base type the function treeMap could have the following form:
function treeMap(f, tree)
if typeof(tree) == Array{Int64,1}
return map(f, tree)
else
return map( t -> treeMap(f,t), tree)
end
end
This package GitHub - nlw0/ArrayTrees.jl: ArrayTrees for Julia allows you to map a function to an array-of-arrays. You cannot control the depth of the traversal, but in the OP example, and in many practical situations, the tree has the same depth in every branch, and all the elements at the third level are of type Int64, so the package will work if this is specified as the leaf type. Specifying Vector{Int64} as the leaf type would allow you to traverse on the second-to-last level.