Julia Functions

A function is a set of statements that together perform a task.

In Julia, a function is an object that maps a tuple of argument values to a return value.

In Julia, usefunctionThe basic syntax for defining a function is:

function functionname(args)
   expression
   expression
   expression
   ...
   expression
end

By default, the value returned by a function is the value of the last evaluated expression, so you can see that above there is noreturnstatement. Of course, if you usereturnkeyword, the function will return immediately:.

Example

julia> function f(x,y)
           x + y
       end
f (generic function with 1 method)
julia> f(2,3)
5

julia> function bills(money)
      if money < 0
         return false
      else
         return true
      end
   end
bills (generic function with 1 method)

julia> bills(50)
true

julia> bills(-50)
false

If a function needs to return multiple values, you can use a tuple:

Example

julia> function mul(x,y)
                  x+y, x*y
               end
mul (generic function with 1 method)

julia> mul(5, 10)
(15, 50)

When a function contains only one expression, you can omit thefunctionkeyword, set the function name and parameters on the left side of the equals sign, and set the expression on the right side, similar to an assignment form:

julia> f(x,y) = x + y
f (generic function with 1 method)

When there are no parentheses, the expressionfrefers to the function object, which can be passed around like any value:

julia> g = f;
julia> g(2,3)
5

Example

julia> f(a) = a * a
f (generic function with 1 method)

julia> f(5)
25

julia> func(x, y) = sqrt(x^2 + y^2)
func (generic function with 1 method)

julia> func(5, 4)
6.4031242374328485

Like variable names, Unicode characters can also be used as function names:

julia> ∑(x,y) = x + y
∑ (generic function with 1 method)

julia> ∑(2, 3)
5

Return Type

We can use the::operator to specify the return type of the function.

Example

julia> function g(x, y)::Int8
           return x * y
       end;

julia> typeof(g(1, 2))
Int8

The above function example ignores the types of x and y and returns a value of type Int8.

Optional Arguments

In functions, we can set default values for parameters, so that when the parameter is not provided, the default value can be used for calculation:

The following example defines a function pos with three parameters, where parameter cz has a default value of 0. When calling the function, this parameter can be omitted:

Example

julia> function pos(ax, by, cz=0)
         println("$ax, $by, $cz")
      end
pos (generic function with 2 methods)

julia> pos(10, 30)
10, 30, 0

julia> pos(10, 30, 50)
10, 30, 50

Keyword Arguments

Sometimes the functions we define require a large number of arguments, but calling these functions can be troublesome because we may forget the order in which to provide the arguments. For example:

function foo(a, b, c, d, e, f)
...
end

We might forget the order of arguments, resulting in the following function call:

foo("25", -5.6987, "hello", 56, good, 'ABC')
或
foo("hello", 56, "25", -5.6987, 'ABC', good)

This looks very confusing.

Julia keyword arguments allow arguments to be identified by name rather than only by position, making these complex functions easy to use and extend.

To mark arguments with keywords, you need to use a semicolon after the unmarked arguments of the function;, followed by one or more key-value pairskey=value, as shown below:

Example

julia> function foo(a, b ; c = 10, d = "hi")
         println("a is $a")
         println("b is $b")
         return "c => $c, d => $d"
      end
foo (generic function with 1 method)

julia> foo(100,20)
a is 100
b is 20
"c => 10, d => hi"

julia> foo("Hello", "Example", c=pi, d=22//7)
a is Hello
b is Example
"c => π, d => 22//7"

With keyword arguments, the position of the arguments is not so important. We can also call the above function like this:

Example

julia> foo(c=pi, d =22/7, "Hello", "Example")
a is Hello
b is Example
"c => π, d => 3.142857142857143"

Anonymous Functions

An anonymous function is a function without a function name.

Anonymous functions are declared dynamically at runtime. Apart from not having a function name, they are the same as standard functions.

In Julia, anonymous functions can be used in many places, such as map() and list comprehensions.

After using anonymous functions, our code becomes more concise.

The syntax of anonymous functions uses the symbol->。

Example

julia> x -> x^2 + 2x - 1
#1 (generic function with 1 method)

julia> function (x)
           x^2 + 2x - 1
       end
#3 (generic function with 1 method)

The above example creates a function that accepts one parameterxand returns the polynomial of the current valuex^2+2x-1function.

The main use of anonymous functions is to pass them to functions that receive functions as arguments. A classic example is map, which applies a function to each element of an array and then returns a new array containing the resulting values:

Example

julia> map(round, [1.2, 3.5, 1.7])
3-element Vector{Float64}:
 1.0
 4.0
 2.0

If the transformation function passed as the first argument to map already exists, then using the function name directly is fine. But usually the function to be used has not been defined yet, so using an anonymous function is more convenient:

Example

julia> map(x -> x^2 + 2x - 1, [1, 3, -1])
3-element Vector{Int64}:
  2
 14
 -2

Anonymous functions that accept multiple arguments can be written using the syntax (x,y,z)->2x+y-z, while zero-argument anonymous functions are written as ()->3. This way of writing zero-argument functions may look a bit strange, but it is very necessary for lazy evaluation. This usage wraps a code block into a zero-argument function and later calls it as f.

For example, consider the call to get:

Example

get(dict, key) do
    # default value calculated here
    time()
end

The above code is equivalent to calling get with an anonymous function containing the code. It is wrapped between do and end, as shown below:

get(()->time(), dict, key)

Here, the call to time is delayed by a zero-argument anonymous function wrapping it. This anonymous function is called only when dict lacks the requested key.


Function Nesting and Recursion

In Julia, functions can be nested.

The following example nests an add1 function inside the add() function:

Example

julia> function add(x)
         Y = x * 2
         function add1(Y)
           Y += 1
         end
         add1(Y)
       end
add (generic function with 1 method)

julia> d = 10
10

julia> add(d)
21

Similarly, functions in Julia can also be recursive.

Recursion refers to the method of using the function itself within the definition of a function.

For example:
Once upon a time there was a mountain, in the mountain there was a temple, in the temple there was an old monk telling a story to a young monk! What was the story? "Once upon a time there was a mountain, in the mountain there was a temple, in the temple there was an old monk telling a story to a young monk! What was the story? 'Once upon a time there was a mountain, in the mountain there was a temple, in the temple there was an old monk telling a story to a young monk! What was the story? ...'"

Below we use the ternary operator to test recursion. The ternary operator operates on three operandsexpr ? a : b, if expr is true, the value is the result of evaluating a, otherwise it is the result of evaluating b.

Example

julia> sum(x) = x > 1 ? sum(x-1) + x : x
sum (generic function with 1 method)

julia> sum(10)
55

The above example is used to calculate the sum of all numbers up to and including a certain integer. In this recursion, because there is a base case, that is, when x is 1, this value is returned.

The most famous example of recursion is calculating the nth Fibonacci number. The Fibonacci sequence is a sequence like this: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368........

Starting from the 3rd term, each term in this sequence is equal to the sum of the previous two terms.

Example

julia> fib(x) = x < 2 ? x : fib(x-1) + fib(x-2)
fib (generic function with 1 method)

julia> fib(10)
55

julia> fib(20)
6765

Map

The Map definition format is as follows:

map(func, coll)

Here, func is a function that is applied to each element of the collection coll in turn. Map generally contains an anonymous function and returns a new collection.

Example

julia> map(A -> A^3 + 3A - 3, [10,3,-2])
3-element Array{Int64,1}:
 1027
   33
  -17

Filter

The Filter definition format is as follows:

filter(function, collection)

The filter function returns a copy of the collection, removing elements for which the result of calling the function is false.

Example

julia> array = Int[1,2,3]
3-element Array{Int64,1}:
 1
 2
 3
 
julia> filter(x -> x % 2 == 0, array)
1-element Array{Int64,1}:
 2
Other Extensions