Parametric polymorphism: Difference between revisions

Content added Content deleted
Line 758: Line 758:
end
end


Tree(v::T) where {T} = Tree(v, nothing, nothing) # Single arg constructor
Tree(v::T) where T = Tree(v, nothing, nothing) # Single arg constructor


"""
"""
Applies `f` (element-wise and in-place) to the values in tree `bt`.
Apply `f` (element-wise and in-place) to the values in tree `bt`.
Prints the tree in an s-expression form *for demonstrative purposes only*,
Also prints the tree like an s-expression *for demonstrative purposes only*,
new types should override the `show()` function for pretty-printing.
new types should override the `show()` function for pretty-printing.
"""
"""
function map!(f::Function, bt::Tree{T}) where T
function map!(f::Function, bt::Tree{T}) where T
bt.val = f(bt.val)
bt.val= f(bt.val)
print(" (" * string(bt.val)) # Demo only
print(" (" * string(bt.val)) # Demonstration only
bt.lchild !== nothing && map!(f, bt.lchild)
bt.lchild !== nothing && map!(f, bt.lchild)
bt.rchild !== nothing && map!(f, bt.rchild)
bt.rchild !== nothing && map!(f, bt.rchild)
print(")") # Demo only
print(")") # Demonstration only
end
end


function test_treemap()
function test_treemap()
bt = Tree(0,
inttree = Tree(0,
Tree(1,
Tree(1,
Tree(3),
Tree(3),
Tree(5)),
Tree(5)),
Tree(2,
Tree(2,
Tree(4),
Tree(4),
Tree(6)))
nothing))
map!(x -> 2x^2, bt)
map!(x -> 2x^2, inttree) # Pass an anonymous function
# (0 (2 (18) (50)) (8 (32) (72)))
# (0 (2 (18) (50)) (8 (32)))
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>
end</lang>