Parametric polymorphism: Difference between revisions

(Added C3 example)
Line 776:
 
=={{header|Julia}}==
{{works with|Julia|1.3.16}}
 
<lang julia>mutablemodule struct Tree{T}BinaryTrees
 
val::T
mutable struct BinaryTree{V}
lchild::Union{Tree{T}, Nothing}
valv::TV
rchild::Union{Tree{T}, Nothing}
lchildl::Union{TreeBinaryTree{TV}, Nothing}
rchildr::Union{TreeBinaryTree{TV}, Nothing}
end
 
TreeBinaryTree(v::T) where T = TreeBinaryTree(v, nothing, nothing) # Single arg constructor
 
map(f, bt::BinaryTree) = BinaryTree(f(bt.v), map(f, bt.l), map(f, bt.r))
map(f, bt::Nothing) = nothing
 
let inttree = TreeBinaryTree(0,
0,
BinaryTree(
Tree(1,
TreeBinaryTree(23),
TreeBinaryTree(5)),
),
BinaryTree(
Tree("foo"2,
TreeBinaryTree(4),
nothing),
),
)
map!(x -> 2x^2, inttree) # Pass an anonymous function
end
 
let strtree = BinaryTree(
"""
strtree = Tree( "hello",
Apply `f` (element-wise and in-place) to the values in tree `bt`.
BinaryTree(
Also prints the tree like an s-expression *for demonstrative purposes only*,
Tree("world!",
new types should overload the `show()` function for pretty-printing.
TreeBinaryTree("Julia"),
"""
nothing)),
function map!(f::Function, bt::Tree{T}) where T
bt.val= f(bt.val ),
BinaryTree(
print(" (" * string(bt.val)) # Demonstration only
Tree("barfoo"),
bt.lchild !== nothing && map!(f, bt.lchild)
TreeBinaryTree("bazbar"))),
bt.rchild !== nothing && map!(f, bt.rchild)
TreeBinaryTree(3"baz"),
print(")") # Demonstration only
),
)
map!(uppercase, strtree)
end
 
function test_treemap()
inttree = Tree(0,
Tree(1,
Tree(3),
Tree(5)),
Tree(2,
Tree(4),
nothing))
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>
 
Anonymous user