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
This exercise is part of the course
Intermediate Julia
Exercise instructions
- Create a function
largest_value
which:- if the input is
String
, usemap
to map thelength
function 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!
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# 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"))