Parametric polymorphism: Difference between revisions
Content added Content deleted
(Added C3 example) |
|||
Line 776: | Line 776: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{works with|Julia|1. |
{{works with|Julia|1.6}} |
||
<lang julia> |
<lang julia>module BinaryTrees |
||
⚫ | |||
mutable struct BinaryTree{V} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
end |
end |
||
BinaryTree(v) = BinaryTree(v, nothing, nothing) |
|||
map(f, bt::BinaryTree) = BinaryTree(f(bt.v), map(f, bt.l), map(f, bt.r)) |
|||
map(f, bt::Nothing) = nothing |
|||
⚫ | |||
0, |
|||
BinaryTree( |
|||
⚫ | |||
⚫ | |||
⚫ | |||
), |
|||
BinaryTree( |
|||
⚫ | |||
⚫ | |||
⚫ | |||
), |
|||
) |
|||
⚫ | |||
end |
|||
let strtree = BinaryTree( |
|||
""" |
|||
⚫ | |||
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*, |
|||
⚫ | |||
new types should overload the `show()` function for pretty-printing. |
|||
⚫ | |||
""" |
|||
⚫ | |||
function map!(f::Function, bt::Tree{T}) where T |
|||
), |
|||
BinaryTree( |
|||
print(" (" * string(bt.val)) # Demonstration only |
|||
⚫ | |||
bt.lchild !== nothing && map!(f, bt.lchild) |
|||
⚫ | |||
bt.rchild !== nothing && map!(f, bt.rchild) |
|||
⚫ | |||
print(")") # Demonstration only |
|||
), |
|||
) |
|||
⚫ | |||
end |
end |
||
function test_treemap() |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
# (0 (2 (18) (50)) (8 (32))) |
|||
println() |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
# (HELLO (WORLD! (JULIA)) (FOO (BAR) (BAZ))) |
|||
end</lang> |
end</lang> |
||