logo

Julia's Exclamation Point Convention 📂Julia

Julia's Exclamation Point Convention

Overview 1

In Julia, appending an exclamation mark ! at the very end of a function name is referred to as the bang convention. Such functions are characterized by modifying the arguments they are given.

Code

function add_1!(x)
    x .+= 1
    return x
end

foo = [2,5,-1]
add_1!(foo)
foo

For example, executing the code above yields the following result.

julia> foo = [2,5,-1]
3-element Vector{Int64}:
  2
  5
 -1

julia> add_1!(foo)
3-element Vector{Int64}:
 3
 6
 0

julia> foo
3-element Vector{Int64}:
 3
 6
 0

The array foo was defined outside the function and was not only returned with each element increased by $1$ through add_1!(), but the argument itself was modified.

Description

A representative method, pop!(), deletes the last element of an array while also returning it. If this function couldn’t modify the original array, users familiar with general programming would have found it difficult to use widely recognized data structures as is the case with Matlab or R, making it cumbersome.

It can be perceived similarly to how in Python, using a method instead of a function can change the data of a class. While not an exact explanation due to Julia’s design not supporting classes, it can still be conveniently used like the methods in Python when that feels more intuitive.

Environment

  • OS: Windows
  • julia: v1.7.0