Define And Use Functions In Julia

Last Updated on

This post is about how to define and use functions in Julia. A function is a block of codes that performs a specific operation. It may accept parameters which may influence its behavior. It may also return values to codes calling the function.

How To Define Functions

We define functions in Julia using the function and end keywords. Consider the following codes.

The function name is my_sum. It accepts two parameters and returns a value of type Int8. Alternatively, we can define a compact function. Consider the following codes that are equivalent to the previous codes.

If we do not specify the data type of parameters and return value, we can pass any values. Julia determines the type dynamically during runtime. Consider the following Julia codes that define the anytype function.

The following codes are equivalent.

We get the following output in Julia when we use the function with different values.

The first example passes a numeric value and gets the same amount. Next, the second example gives a String value and returns the equal value. Lastly, the third example passes an array of String values and gets the same value.

We can also define functions in Julia that don’t accept any parameters and returns nothing. Consider these codes.

We can also define a function that accepts zero or multiple parameters using the ... operator after a parameter name.

A function in Julia does not need a name, and we can define an anonymous function.

How To Use Functions

Before we can use a function, we must define it first. Meaning, the function definition comes first before its usage. Otherwise, we get an UndefVarError error. Consider the following codes.

To fix this, we need to define the function before using it.

If we want to make this function compact, we could define it as follows.

Defining functions is also the way to “implement” interfaces in Julia.

Karl San Gabriel

Karl San Gabriel

Professional Software Developer