Multiple dispatch
Multiple dispatch is one of Julia's significant advantages, providing flexibility and speed benefits to your Julia programs. Remember, multiple dispatch allows you to run a different method based on the type of the argument passed into a function.
The example in the video used multiple dispatch to return a different value depending on whether the argument type was a string or not.
function add_values(x, y)
x + y
end
function add_values(x::String, y::String)
x * y
end
Bài tập này là một phần của khóa học
Intermediate Julia
Hướng dẫn bài tập
- Create a function
largest_valuewhich:- if the input is
String, usemapto map thelengthfunction to each argument(x, y, z). - if the input is
Bool, simply return the arguments. - if the input is any other type, get the maximum of all values using
maximum.
- if the input is
- Remove the commented-out lines at the bottom (the test cases) and ensure that the logic makes sense!
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# Create three functions to handle any input, String input, and Bool input
function largest_value(x, y, z)
maximum((____, ____, ____))
end
function largest_value(x::____, y::____, z::____)
map(length, (____, ____, ____))
end
function largest_value(x::____, y::____, z::____)
x, y, z
end
# Un-comment this test case to test your function
#println(largest_value("12", "24", "36"))