Parametric polymorphism: Difference between revisions
Content added Content deleted
Line 758: | Line 758: | ||
end |
end |
||
Tree(v::T) where |
Tree(v::T) where T = Tree(v, nothing, nothing) # Single arg constructor |
||
""" |
""" |
||
Apply `f` (element-wise and in-place) to the values in tree `bt`. |
|||
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 |
bt.val= f(bt.val) |
||
print(" (" * string(bt.val)) # |
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(")") # |
print(")") # Demonstration only |
||
end |
end |
||
function test_treemap() |
function test_treemap() |
||
inttree = Tree(0, |
|||
Tree(1, |
Tree(1, |
||
Tree(3), |
Tree(3), |
||
Tree(5)), |
Tree(5)), |
||
Tree(2, |
Tree(2, |
||
Tree(4), |
Tree(4), |
||
nothing)) |
|||
map!(x -> 2x^2, |
map!(x -> 2x^2, inttree) # Pass an anonymous function |
||
# |
# (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> |
||