Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Julia Functions

Julia Functions

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

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


Defining a function

In Julia, functions are defined with function; the basic syntax is:

function functionname(args)

   expression

   ...

end

By default, the value returned by a function is the value of the last evaluated expression, so the above form has no return statement. Of course, if the return keyword is used, the function returns immediately:

Example

julia

function

f

(

x, y

)

           x + y

       

end

f

(

generic

function

with

1

method

)

julia

f

(

2

,

3

)

5

Use return for an early return

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

When the function body has only one expression, the function keyword can be omitted and the function can be defined in assignment form, which is a very common style in Julia:

Example

julia

f

(

x, y

)

= x + y

f

(

generic

function

with

1

method

)

julia

f

(

2

,

3

)

5

julia

func

(

x, y

)

= sqrt

(

x^

2

2

)

func

(

generic

function

with

1

method

)

julia

func

(

5

,

4

)

6.4031242374328485

Without parentheses, the expression f refers to the function object and can be passed around like any value:

Example

julia

g = f

;

julia

g

(

2

,

3

)

5

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

Example

julia

∑

(

x, y

)

= x + y

∑

(

generic

function

with

1

method

)

julia

∑

(

2

,

3

)

5


Argument type declarations

You can declare an argument type after the argument name with :: to restrict the range of types the function applies to:

Example

Accept only integer-type arguments

julia

fib

(

n::

Integer

)

= n

<

=

2

?

1

: fib

(

n-

1

)

(

n-

2

)

fib

(

generic

function

with

1

method

)

julia

fib

(

10

)

55

julia

fib

(

1.5

)

ERROR: MethodError: no method matching fib

(

::

Float64

)

Note:Declaring types for arguments does not improve performance (Julia automatically compiles specialized versions for the actual types passed); its main roles are to restrict dispatch, ensure correctness, and improve readability. When unsure, you can omit the type declaration or use broader abstract types such as Integer or Real.


Return types and multiple return values

We can use the :: operator after the function signature to specify the return type:

Example

julia

function

g

(

x, y

)

::

Int8

           

return

x

y

       

end

;

julia

typeof

(

g

(

1

,

2

)

)

Int8

The above function example converts the return value to type Int8. Note that return type declarations are rarely used in Julia; writing type-stable functions is the better approach.

If a function needs to return multiple values, you can use a tuple and receive it via destructuring at the call site:

Example

julia

function

mul

(

x, y

)

           x + y, x

y

       

end

mul

(

generic

function

with

1

method

)

julia

mul

(

5

,

10

)

(

15

,

50

)

Destructuring assignment receives multiple return values

julia

s, p = mul

(

5

,

10

)

(

15

,

50

)

julia

s

15

Convention:By convention, a function that only produces side effects and returns no meaningful result should explicitly return nothing.


Optional arguments

In a function we can set default values for arguments, so that when the argument is not provided the default value can be used in the computation:

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

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 use keyword arguments, place a semicolon ; after the positional arguments of the function, followed by one or more key=value pairs:

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"

,

"Runoob"

, c=pi, d=

22

//

7

)

a is Hello

b is Runoob

"c => π, d => 22//7"

Important:When calling, positional arguments must be written before keyword arguments, and keyword arguments may be arranged in any order, for example foo("Hello", "Runoob", d=22//7, c=pi) is also correct. But foo(c=pi, "Hello", "Runoob") this style with keywords before positional arguments iswrong, and will directly report a MethodError.

Keyword arguments that are not matched can be collected with kwargs..., which is a named tuple:

Example

julia

function

f

(

x

;

y=

0

, kwargs...

)

           

println

(

"x = $x, y = $y"

)

           

println

(

"Other keywords: $kwargs"

)

       

end

f

(

generic

function

with

1

method

)

julia

f

(

1

;

a=

2

, b=

3

)

x =

1

, y =

0

Other keywords:

(

a =

2

, b =

3

)


Variadic functions (Varargs)

Adding ... after the last positional argument lets you define a function that accepts any number of arguments; the extra arguments are collected into a tuple:

Example

julia

bar

(

a, b, x...

)

=

(

a, b, x

)

bar

(

generic

function

with

1

method

)

julia

bar

(

1

,

2

)

(

1

,

2

,

(

)

)

julia

bar

(

1

,

2

,

3

,

4

)

(

1

,

2

,

(

3

,

4

)

)

Conversely, when calling a function, ... can "splat" a collection into individual arguments:

Example

julia

x =

(

3

,

4

)

(

3

,

4

)

julia

bar

(

1

,

2

, x...

)

(

1

,

2

,

(

3

,

4

)

)

julia

max

(

[

1

,

5

,

3

]

...

)

5


Anonymous functions

An anonymous function is a function without a name, using the symbol -> in its syntax:

Example

julia

x -

x^

2

1

#1 (generic function with 1 method)

julia

function

(

x

)

           x^

2

1

       

end

#3 (generic function with 1 method)

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

Example

julia

map

(

round

,

[

1.2

,

3.5

,

1.7

]

)

3

-element

Vector

{

Float64

}

:

 

1.0

 

4.0

 

2.0

julia

map

(

x -

x^

2

1

,

[

1

,

3

, -

1

]

)

3

-element

Vector

{

Int64

}

:

 

2

 

14

 -

2

An anonymous function taking multiple arguments can use the syntax (x,y,z) -> 2x+y-z, while a no-argument anonymous function is written ()->3.

The do block

When you need to pass a multi-line anonymous function to a function, you can use a do block to make the code look more like an ordinary code block:

Example

The following two forms are completely equivalent

julia

map

(

x -

begin

           

if

x

<

0

return

0

elseif

x ==

0

               

return

1

           

else

               

return

x

           

end

       

end

,

[

2

,

0

,

3

]

)

3

-element

Vector

{

Int64

}

:

 

0

 

1

 

3

Using a do block is clearer

julia

map

(

[

2

,

0

,

3

]

)

do

x

           

if

x

<

0

return

0

elseif

x ==

0

               

return

1

           

else

               

return

x

           

end

       

end

3

-element

Vector

{

Int64

}

:

 

0

 

1

 

3

The do x syntax creates an anonymous function with x as its argument and passes it as the first argument to the outer function.

The most common use of do blocks is resource management; for example, the open function ensures the file is eventually closed:

Example

open

(

"outfile.txt"

,

"w"

)

do

io

   

write

(

io,

"RUNOOB"

)

end

Its implementation is roughly as follows: open first opens the file and uses try/finally to ensure the file is closed whether or not the function throws an exception:

function open(f::Function, args...)

    io = open(args...)

    try

        f(io)

    finally

        close(io)

    end

end


Function composition and piping

Julia provides two convenient operators for composing functions.

∘ (type \circ then press Tab) is the function composition operator; (f ∘ g)(x) is equivalent to f(g(x)):

Example

julia

(

sqrt ∘ +

)

(

3

,

6

)

3.0

julia

map

(

first ∘

reverse

∘

uppercase

,

split

(

"you can compose functions like this"

)

)

6

-element

Vector

{

Char

}

:

 

'U'

: ASCII/Unicode U+0055

(

category Lu: Letter,

uppercase

)

 

'N'

: ASCII/Unicode U+004E

(

category Lu: Letter,

uppercase

)

 

'E'

: ASCII/Unicode U+0045

(

category Lu: Letter,

uppercase

)

 

'S'

: ASCII/Unicode U+0053

(

category Lu: Letter,

uppercase

)

 

'E'

: ASCII/Unicode U+0045

(

category Lu: Letter,

uppercase

)

 

'S'

: ASCII/Unicode U+0053

(

category Lu: Letter,

uppercase

)

|> is the pipe operator, which passes the value on the left as an argument to the function on the right, making the flow of data processing more intuitive:

Example

1:10 |> sum |> sqrt is equivalent to sqrt(sum(1:10)) julia> 1:10 |> sum |> sqrt 7.416198487095663 [/mycode4]


Dot syntax vectorization

Any function f can be applied element-wise to an array via the f.(A) syntax, equivalent to broadcast(f, A):

Example

julia

A =

[

1.0

,

2.0

,

3.0

]

;

julia

sin.

(

A

)

3

-element

Vector

{

Float64

}

:

 

0.8414709848078965

 

0.9092974268256817

 

0.1411200080598672

Multi-argument functions can also be broadcast

julia

f

(

x, y

)

= 3x + 4y

f

(

generic

function

with

1

method

)

julia

f.

(

A,

[

10

,

20

,

30

]

)

3

-element

Vector

{

Float64

}

:

 

43.0

 

86.0

129.0

Nested dot calls are automaticallyfusedinto a single loop; X .= f.(Y) can also write the result into X in place, see for detailsarraysThe broadcast section of the chapter.


Map and Filter

map(func, coll) applies the function to each element of the collection coll in turn, returning a new collection:

Example

julia

map

(

A -

A^

3

3

,

[

10

,

3

, -

2

]

)

3

-element

Vector

{

Int64

}

:

 

1027

   

33

  -

17

filter(function, collection) returns a copy of the collection, keeping only the elements for which the function returns true:

Example

julia

array =

[

1

,

2

,

3

,

4

,

5

,

6

]

;

julia

filter

(

x -

x

%

2

==

0

, array

)

3

-element

Vector

{

Int64

}

:

 

2

 

4

 

6


Nested Functions and Recursion

In Julia, functions can be nested. Inner functions can access the variables of the outer function:

Example

julia

function

add

(

x

)

           y = x

2

           

function

add1

(

y

)

               

return

y +

1

           

end

           

return

add1

(

y

)

       

end

add

(

generic

function

with

1

method

)

julia

add

(

10

)

21

Likewise, functions in Julia can also be recursive. Recursion refers to using the function itself within its own definition.

Below we use the ternary operator to write recursion. The ternary operator expr ? a : b evaluates to the result of a if expr is true, otherwise to the result of b:

Example

julia

mysum

(

x

)

= x

1

?

mysum

(

x-

1

)

mysum

(

generic

function

with

1

method

)

julia

mysum

(

10

)

55

The most famous example of recursion is computing the nth Fibonacci number:

Example

julia

fib

(

x

)

= x

<

2

?

x : fib

(

x-

1

)

(

x-

2

)

fib

(

generic

function

with

1

method

)

julia

fib

(

10

)

55

julia

fib

(

20

)

6765

Tip:The directly recursive fib becomes very slow around fib(50) (exponential complexity). In practice you can use a dictionary to cache intermediate results, or switch to an iterative implementation.