Functions#
Learning Objectives#
Define and create functions in Julia
Understand and use lambda (anonymous) functions
Implement multiple dispatch in Julia to handle different types of inputs
Utilize functions to organise and modularize code
Recognize the benefits of using multiple dispatch for flexibility, performance and extensibility
Defining Functions#
Within Julia, functions are defined using the function
keyword. A function can return values explicitly with return
. The following defines a function for calculating the area of a circle
function calculate_circle_area(radius::Float64)
area = 3.14 * radius^2
return area
end
radius = 5.0
println("Radius: ", radius, " Area: ", calculate_circle_area(radius))
Radius: 5.0 Area: 78.5
There are three main components to a Julia function:
- Function Name: In the above function this is calculate_circle_area
- Parameter: In the above function this is radius
. The syntax of ::Float64
denotes type annotation for double precision floating point numbers.
- Returns: The computed area using the const
To then make use of the function there is a need to call the function with the argument for the parameter, seen in the above with calculating the area of a circle with a radius of 5.
Lambda (Anonymous) Functions#
Lambda functions are functions that are not bound to a name and often used as short code snippets that are passed onto higher-order functions. An example definition and usage of a lambda function can be seen below.
numbers = [1,2,3,4,5]
squared_numbers = map(x -> x * x, numbers)
println(squared_numbers)
[1, 4, 9, 16, 25]
Multiple Dispatch#
Multiple dispatch is a key feature of Julia, where the function that is called depends on the runtime types of all arguments, allowing for efficient and flexible code. Below is an example defining multiple version of an “add” function, where each handles a different type of input.
# Function for adding two numbers together
add(x::Int, y::Int) = x + y
# Function for concatenating string
add(x::String, y::String) = x * " " * y
println(add(10,20))
println(add("Hello","world!"))
30
Hello world!
The use of multiple dispatch has a range of different benefits including:
Flexibility: Functions can be written in a generic manner, with specific behaviour implemented for specific types.
Performance: Julia is able to optimize the method calls at runtime, leading to efficient code execution.
Extensibility: New types can be introduced without requiring existing code modification.