Julia Functions
A function is a named block of code that does one job. You write it once and call its name whenever you need that job done.
Define and call a function
The long form names the function and lists its argument. Calling it twice runs the same block twice.
function double(x)
x * 2
end
println(double(4))
println(double(9))The short form fits on one line
A small function can be written as a name, its argument, and one expression. The expression gives the result.
square(x) = x * x
println(square(5))
println(square(3))A function can take two arguments
Two arguments are listed in order inside the parentheses. The call passes two values in that same order.
function add(a, b)
a + b
end
println(add(3, 4))
println(add(10, 5))Example
function greet(name)
"Hello, " * name
end
triple(x) = x * 3
function add(a, b)
a + b
end
println(greet("Ana"))
println(triple(4))
println(add(2, 6))Key points
- Function: a reusable block of code with a name.
- Long form: the word function starts the block and the word end closes it.
- Call: write the function name, then the values in parentheses.
- Argument: a value passed into a function when it is called.
- Short form: name(x) = expression defines a small function in one line.
- Two arguments: list them inside the parentheses, separated by a comma.
In this example, greet uses the long form and joins text with the name it receives. Next, triple uses the short form and multiplies its argument by 3. Last, add takes two arguments and returns their sum, which prints as 8.
Note
Julia programs are built from many small functions, each doing one job.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
After double(x) = x * 2 is defined, what does println(double(6)) print?