Aan de slagGa gratis aan de slag

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

Deze oefening maakt deel uit van de cursus

Intermediate Julia

Cursus bekijken

Oefeninstructies

  • Create a function largest_value which:
    • if the input is String, use map to map the length 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.
  • Remove the commented-out lines at the bottom (the test cases) and ensure that the logic makes sense!

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# 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"))
Code bewerken en uitvoeren