Title here
Summary here
Functions are central in Julia. We’ll learn about functions with a few different examples.
# Here's a function that takes two integers and returns
# their sum as an integer.
function plus(a::Int, b::Int)::Int
# Julia automatically returns the value of the last expression,
# but we can use the `return` keyword for clarity.
return a + b
end
# In Julia, we can define multiple methods for the same function
# with different argument types. This is called multiple dispatch.
function plusplus(a::Int, b::Int, c::Int)::Int
return a + b + c
end
# The main function in Julia is not required, but we'll use it
# to organize our code.
function main()
# Call a function just as you'd expect, with `name(args)`.
res = plus(1, 2)
println("1+2 = ", res)
res = plusplus(1, 2, 3)
println("1+2+3 = ", res)
end
# Call the main function
main()
To run the program, save it as functions.jl
and use the Julia REPL or command line:
$ julia functions.jl
1+2 = 3
1+2+3 = 6
There are several other features to Julia functions. One is multiple return values, which we’ll look at next.