Parametric polymorphism: Difference between revisions

m
Line 758:
end
 
Tree(v::T) where {T} = Tree(v, nothing, nothing) # Single arg constructor
 
"""
AppliesApply `f` (element-wise and in-place) to the values in tree `bt`.
PrintsAlso prints the tree inlike 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)) # DemoDemonstration only
bt.lchild !== nothing && map!(f, bt.lchild)
bt.rchild !== nothing && map!(f, bt.rchild)
print(")") # DemoDemonstration only
end
 
function test_treemap()
btinttree = Tree(0,
Tree(1,
Tree(3),
Tree(5)),
Tree(2,
Tree(4),
Tree(6) nothing))
map!(x -> 2x^2, btinttree) # Pass an anonymous function
# (0 (2 (18) (50)) (8 (32) (72)))
println()
strtree = Tree("hello",
Tree("world!",
Tree("Julia"),
nothing),
Tree("foo",
Tree("bar"),
Tree("baz")))
map!(uppercase, strtree)
# (HELLO (WORLD! (JULIA)) (FOO (BAR) (BAZ)))
end</lang>
 
Anonymous user