Anonymous user
Parametric polymorphism: Difference between revisions
→{{header|Julia}}
(omit: Bc Dc) |
|||
Line 750:
=={{header|Julia}}==
{{works with|Julia|
<lang julia>mutable struct Tree{T}
lchild::
rchild::
end
# Constructor with default values
function
Tree(v, nothing, nothing)
end
"""
Apply `f` (element-wise and in-place) to the values in tree `bt`.
Also prints the tree in an s-expression form *for demonstrative purposes only*,
new types should override the `show()` function for pretty-printing.
"""
function map!(f::Function, bt::Tree{T}) where T
bt.val= f(bt.val)
print(" (" * string(bt.val)) # Demo only
bt.lchild !== nothing && map!(f, bt.lchild)
bt.rchild !== nothing && map!(f, bt.rchild)
print(")") # Demo only
end
function test_treemap()
bt = Tree(0,
Tree(1,
Tree(3),
Tree(5)),
Tree(2,
Tree(4),
Tree(6)))
map!(x -> 2x^2, bt)
# (0 (2 (18) (50)) (8 (32) (72)))
end</lang>
|