Parametric polymorphism: Difference between revisions

(omit: Bc Dc)
Line 750:
 
=={{header|Julia}}==
{{works with|Julia|01.63.1}}
{{trans|C++}}
 
<lang julia>mutable struct Tree{T}
valueval::T
lchild::NullableUnion{Tree{T}, Nothing}
rchild::NullableUnion{Tree{T}, Nothing}
end
 
# Constructor with default values
function replaceall!(t::Tree{T}, (v::T) where T
t.value = v
Tree(v, nothing, nothing)
isnull(lchild) || replaceall(get(lchild), v)
end
isnull(rchild) || replaceall(get(rchild), v)
 
return t
"""
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>
 
Anonymous user