Engee documentation

Functions

Functions are the basic building blocks of a programme. They allow you to organise your code, make it more readable and reusable. In Julia, functions can be simple or complex, depending on the task at hand. If you’re just starting out on your programming journey, functions are something you’ll be working with all the time. They help you break down complex tasks into smaller, more manageable pieces.

Defining a function

Functions in Julia are defined using the function keyword. They can return values using return or automatically return the result of the last expression. Let’s look at an example:

function fname(x, y)
  z = x^2
  z + 4y
end

In this example, the function fname takes two arguments x and y, calculates the square of x and adds 4y to it. The result of the last expression (z + 4y) is automatically returned as the result of the function.

For a more compact function definition, you can use the abbreviated syntax:

gname(x, y) = x^2 + 4y

This syntax is convenient for simple functions that can be written in a single line. It makes the code more concise and easy to read.

Function call

Functions are called by name with arguments passed in parentheses. This allows you to perform calculations and get results. For example:

z = fname(3, 1)
Output
9

Here, the function fname is called with arguments 3 and 1 and the result is stored in the variable z.

Example with comments

# Функция для вычисления площади прямоугольника
function calculate_area(width, height)
  area = width * height  # Вычисляем площадь
  return area  # Возвращаем результат
end

# Вызов функции и вывод результата
result = calculate_area(5, 10)
println("Площадь прямоугольника: ", result)
Output
Площадь прямоугольника: 50

Useful tips

  • Use meaningful names - name functions so that their purpose is clear at a glance. For example, calculate_function is better than func1.

  • Divide code into smaller functions - if a function becomes too large, divide it into several smaller functions. This will make the code easier to read and debug.

  • Comment the code - add comments to functions to explain what they do and how to use them. In Julia, comments start with the # symbol.

  • Test functions - test your functions on different inputs to make sure they work properly.

  • Use return values - don’t forget that functions can return results that can be used in other parts of the programme. Return values are what a function "gives back" after it has been executed. For example, if a function calculates the sum of two numbers, its result can be stored in a variable or passed to another function for further processing. This makes functions versatile and allows you to build complex programmes from simple components. Always think about how the result of a function can be useful in other parts of your code.