Defining functions

There are actually two different syntaxes that we can use to define a function:

  • The first way is a simple one-liner that contains both the signature and body of the function.
  • The second way uses the function keyword with the signature, followed by the code block and the end keyword.

If the function is simple enough—for example, if it just has a single instruction—then it is usually more preferable to write the function in a single line. This style of function definition is very common for scientific computing projects, as many functions simply mimic the corresponding mathematical formulae.

For our game, we can just write four functions for moving the game pieces around the board by modifying the coordinates of the widget:

# single-line functions
move_up!(widget, v) = widget.position.y -= v
move_down!(widget, v) = widget.position.y += v
move_left!(widget, v) = widget.position.x -= v
move_right!(widget, v) = widget.position.x += v

It is indeed quite idiomatic in Julia to write single-line functions. People coming from a different background may find it more intuitive to write the following, more verbose, form. There is nothing wrong with this; both forms work just fine:

# long version
function move_up!(widget, v)
widget.position.y -= v
end

There are a few things to bear in mind about how these functions are written:

  • Use of underscore: The preceding function names use an underscore to separate the words. According to the official Julia manual, the convention is to just smash the words together without any separators unless it becomes too confusing or hard to read. My personal opinion is that underscore should always be used for multi-word function names because it enhances the readability and makes the code more consistent.
  • Use of exclamation mark: The preceding function names contain exclamation mark to indicate that the function mutates the state of the object that is being passed into the function. This is a good practice because it reminds the developer that there will be side effects when calling the function.
  • Duck typing: You may wonder why the function arguments are not annotated with any type information. In the move_up! function, although we do not have any type annotation, we expect the widget argument to have the Widget type and v to have the Int type when the function is used. This is an interesting topic, and we will discuss it further in the next section.

As you can see, defining functions is a fairly straightforward task, and the way Julia handles function arguments is quite interesting. We will go over this next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.198.173