Parametric polymorphism: Difference between revisions
Content added Content deleted
(omit: Bc Dc) |
|||
Line 750: | Line 750: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{works with|Julia| |
{{works with|Julia|1.3.1}} |
||
{{trans|C++}} |
|||
<lang julia>mutable struct Tree{T} |
<lang julia>mutable struct Tree{T} |
||
val::T |
|||
lchild:: |
lchild::Union{Tree{T}, Nothing} |
||
rchild:: |
rchild::Union{Tree{T}, Nothing} |
||
end |
end |
||
# Constructor with default values |
|||
function |
function Tree(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> |
end</lang> |
||