Learn Julia · 4/15

Functions & Multiple Dispatch

9 min read

Functions & Multiple Dispatch funzioni

Welcome, intrepid coder, to the world of Julia functions! Functions are the building blocks of any program, the loyal minions that carry out your commands. Without them, you'd be stuck writing the same code over and over again, which is about as fun as watching paint dry.

The problem is simple: we're lazy (in a good, efficient programmer way!). We don't want to repeat ourselves. If we need to perform the same set of operations multiple times, we want to package it up, give it a name, and then just call that name whenever we need it.

This is where functions come to the rescue! They are reusable blocks of code that perform a specific task. Think of them as a recipe: you define it once, and then you can use it to bake a cake (or, you know, calculate a value) as many times as you want without having to write down the ingredients and steps each time.


Defining Basic Functions and Return Values 📜

Let's start with the absolute basics. A function in Julia is defined with the function keyword, followed by the function name and a pair of parentheses for arguments, and it ends with the end keyword.

Imagine you're building a simple calculator. You'll need a way to add two numbers. Instead of writing 2 + 3 every time, you can create a function.

julia
function add(x, y)
  return x + y
end

Here's the breakdown:

  • function add(x, y): We're defining a function named add that accepts two arguments, x and y.
  • return x + y: This is the body of the function. It calculates the sum of x and y and, crucially, uses the return keyword to send that value back as the result of the function call.
  • end: This marks the end of the function definition.

Now, you can use your add function like this:

julia
sum_result = add(5, 3)
println(sum_result) # This will print 8

Implicit Returns: A Julia Trick Up Your Sleeve

Julia is a language that values conciseness. In many cases, you can omit the return keyword. The last evaluated expression in a function is automatically returned. So, our add function can be written more compactly:

julia
function add(x, y)
  x + y
end

This works exactly the same as the previous version. It's a common and idiomatic way to write short functions in Julia. It's like telling a friend to "get the total" – you don't need to explicitly say "and then tell me the total." It's implied.

Here's another example, a function to calculate the area of a rectangle:

julia
function calculate_area(length, width)
  length * width
end

area = calculate_area(10, 5)
println(area) # This will print 50

Anonymous Functions and Arrow Syntax 🏹

Sometimes, you need a function for a quick, one-off task, and giving it a formal name feels like overkill. It's like needing a temporary note; you wouldn't get a whole new notebook just for that. This is where anonymous functions come in.

Anonymous functions, as the name suggests, don't have a name. They are often used when passing a function as an argument to another function (a concept we'll explore more later).

The standard syntax for an anonymous function in Julia looks like this:

julia
function(x, y)
  x * y
end

You can assign this to a variable if you want to reuse it, but often you'll see it used directly.

The Slick Arrow Syntax

Julia provides an even more concise way to define simple, single-expression anonymous functions using the arrow -> syntax.

Let's rewrite our anonymous multiplication function using the arrow syntax:

julia
(x, y) -> x * y

This creates a function that takes two arguments, x and y, and returns their product. It's short, sweet, and to the point.

A very common use case for anonymous functions is with functions that operate on collections, like map. The map function applies a given function to each element of a collection.

Imagine you have an array of numbers and you want to double each one. You could write a named function for this, but an anonymous function is perfect for such a simple operation.

julia
numbers = [1, 2, 3, 4, 5]

doubled_numbers = map(x -> x * 2, numbers)

println(doubled_numbers) # This will print [2, 4, 6, 8, 10]

In this example, x -> x * 2 is our anonymous function that takes a single argument x and returns x * 2. The map function then applies this to every number in the numbers array. It's a clean and highly readable way to perform operations on data.


Optional, Keyword Arguments, and Slurping 🍽️

As your functions become more complex, you'll want more flexibility in how you call them. Julia provides several powerful features for this: optional arguments, keyword arguments, and "slurping" (variadic) arguments.

Optional Arguments

Sometimes, you want to provide a default value for an argument. If the user doesn't provide a value for that argument, the default is used. This is called an optional argument.

Let's say we have a function to greet a user. Most of the time, we want to say "Hello," but sometimes we might want a different greeting.

julia
function greet(name, greeting="Hello")
  println("$greeting, $name!")
end

Now, we can call this function in two ways:

julia
greet("Alice")      # This will print "Hello, Alice!"
greet("Bob", "Hi")  # This will print "Hi, Bob!"

In the first call, we didn't provide a value for greeting, so it used the default "Hello". In the second call, we did, so it used "Hi".

Keyword Arguments

When a function has many arguments, it can be hard to remember their order. Keyword arguments solve this problem by allowing you to specify arguments by their name, not their position. You separate keyword arguments from positional arguments with a semicolon ;.

Imagine a function to create a user profile with several optional fields.

julia
function create_user(username; email="", phone="", is_active=true)
  println("Creating user: $username")
  if !isempty(email)
    println("Email: $email")
  end
  if !isempty(phone)
    println("Phone: $phone")
  end
  println("Active: $is_active")
end

Now, we can call this function and provide the arguments in any order we want, as long as we use their names:

julia
create_user("jane_doe"; phone="123-456-7890", email="[email protected]")

This makes the function call much more readable and less error-prone. You don't have to remember if email comes before phone.

Slurping Arguments (Variadic Functions)

What if you want a function to accept a variable number of arguments? For example, a function that sums up all the numbers you pass to it, no matter how many there are. This is where "slurping" comes in. The ... syntax is used to collect multiple arguments into a single tuple.

Let's create that sum_all function:

julia
function sum_all(numbers...)
  total = 0
  for num in numbers
    total += num
  end
  return total
end

Now you can call sum_all with as many numbers as you like:

julia
println(sum_all(1, 2, 3))       # This will print 6
println(sum_all(10, 20, 30, 40)) # This will print 100
println(sum_all(5))             # This will print 5

The numbers... slurps up all the arguments into a tuple called numbers, which we can then iterate over. It's like having an expandable bag that can hold as many items as you want to put in it.


Understanding Multiple Dispatch: Julia's Superpower 💪

Now we arrive at what is arguably Julia's most defining and powerful feature: multiple dispatch.

The problem it solves is this: in many languages, when you call a function, the specific method that gets executed is determined by the name of the function and, in object-oriented languages, by the type of the first argument (the object). This is called single dispatch.

Julia takes a different approach. When you call a function in Julia, the method that gets executed is determined by the types of all the arguments, not just the first one. This is multiple dispatch.

Think of it like this: imagine you have a toolbox. In a single-dispatch language, you have a tool called use and you tell an object, say a hammer, to use itself. The hammer knows what to do.

In Julia, the use function itself is smarter. You'd say use(hammer, nail). Julia would see you have a hammer and a nail and select the method of use specifically designed for hammering nails. If you were to say use(paintbrush, wall), Julia would select a different method of use for painting a wall. The function's behavior dispatches based on the combination of all argument types.

Let's see this in action with a simple example. We'll define a function interact for different types.

First, let's define some simple types:

julia
abstract type Character end
struct Hero <: Character end
struct Villain <: Character end
struct Civilian <: Character end

Now, let's define methods for our interact function. A function in Julia is a collection of methods.

julia
function interact(a::Hero, b::Villain)
  println("The Hero fights the Villain!")
end

function interact(a::Villain, b::Hero)
  println("The Villain cackles and attacks the Hero!")
end

function interact(a::Hero, b::Civilian)
  println("The Hero saves the Civilian!")
end

function interact(a::Character, b::Character)
  println("Two characters meet.")
end

Here's what's happening:

  • We've defined four different methods for the same function, interact.
  • Each method has a different signature, which is the combination of the types of its arguments.
  • interact(a::Hero, b::Villain) will only be called if the first argument is a Hero and the second is a Villain.
  • The last method, interact(a::Character, b::Character), is a fallback that will be called if no more specific method matches.

Now, let's see what happens when we call interact with different combinations of types:

julia
hero = Hero()
villain = Villain()
civilian = Civilian()

interact(hero, villain)    # Prints "The Hero fights the Villain!"
interact(villain, hero)    # Prints "The Villain cackles and attacks the Hero!"
interact(hero, civilian)   # Prints "The Hero saves the Civilian!"
interact(villain, civilian) # Prints "Two characters meet." because no specific method exists for (Villain, Civilian)

This allows for incredibly expressive and efficient code. You can write generic algorithms that behave differently based on the types of data they are operating on, without a bunch of if/else statements to check types. This is a fundamental reason why Julia can be as fast as compiled languages like C while remaining as dynamic and easy to use as Python.

A Fun Fact: The developers of Julia have said that if they could go back and rename "multiple dispatch," they might call it "defining functions by specializing on argument types," which is a bit more descriptive, if less catchy!

References for Further Reading

Challenge

Challenge: Implement Combat Interactions with Multiple Dispatch

Your task is to model a simple combat system using Julia's multiple dispatch. You will define a single function, engage, which behaves differently based on the types of the two characters interacting. You will also add an optional keyword argument to modify the interaction's description.

Requirements:

  1. Define a function engage(a::Character, b::Character). You will need to create multiple methods for this function to handle specific type pairings.
  2. The function should accept an optional keyword argument setting with a default value of "a neutral setting".
  3. Implement the following interaction methods. Each method should return a string describing the action, incorporating the character names and the setting:
    • Warrior engaging a Mage: The Warrior closes the distance. (e.g., "Aragorn closes the distance on Gandalf in the castle.")
    • Mage engaging a Warrior: The Mage casts a defensive spell. (e.g., "Gandalf casts a defensive spell against Aragorn in a neutral setting.")
    • Warrior engaging a Monster: The Warrior performs a heroic strike.
    • Mage engaging a Monster: The Mage unleashes elemental fury.
    • Any Character engaging themself (e.g., Mage and Mage): The character practices their technique.
    • A generic fallback method for any other combination of Character types: The two characters cautiously observe each other.

Expected result

Your code should correctly dispatch to the appropriate method based on the arguments' types and correctly incorporate the optional keyword argument. Given the following character instances:

julia
boromir = Warrior("Boromir", 100)
legolas = Warrior("Legolas", 90)
gandalf = Mage("Gandalf", 80)
saruman = Mage("Saruman", 75)
orc = Monster("Orc Grunt", 40)

Your engage function should produce the following return values for these calls:

  • engage(boromir, gandalf) should return "Boromir closes the distance on Gandalf in a neutral setting."
  • engage(gandalf, boromir, setting="the tower") should return "Gandalf casts a defensive spell against Boromir in the tower."
  • engage(legolas, orc, setting="the forest") should return "Legolas performs a heroic strike against Orc Grunt in the forest."
  • engage(saruman, orc) should return "Saruman unleashes elemental fury on Orc Grunt in a neutral setting."
  • engage(gandalf, saruman) should return "Gandalf practices their technique with Saruman in a neutral setting."
  • engage(orc, boromir) should return "Orc Grunt and Boromir cautiously observe each other in a neutral setting."
julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.