Functions

Function definitions

function f(x, y)
    x += 2
    x + y
end
f (generic function with 1 method)
f(x, y) = x + y
f (generic function with 1 method)
(x, y) = f(x, y)
∑ (generic function with 1 method)
(3, 4)
7

Return statement

function g(x, y)
    return x * y
    x + y
end
g (generic function with 1 method)
g(2, 3)
6

Specifying Types

g(x::Integer, y::Integer)::Int8 = x + y
g (generic function with 2 methods)
typeof(g(2,2))
Int8

Return tuples

function return_tuple(x, y)
    x + 2, y + 2
end
return_tuple (generic function with 1 method)
return_tuple(2, 4)
(4, 6)

Unpacking

a, b = return_tuple(2, 4)
@show a, b;
(a, b) = (4, 6)

Optional Arguments

function optional(x, y=1)
    x + y
end
optional (generic function with 2 methods)
optional(4)
5
optional(4, 3)
7

Keyword arguments

function keywd(x; plus=2)
    x + plus
end
keywd (generic function with 1 method)
keywd(3, plus=3)
6
keywd(3, 3)
MethodError: no method matching keywd(::Int64, ::Int64)
Closest candidates are:
  keywd(::Any; plus) at In[15]:1

Stacktrace:
 [1] top-level scope
   @ In[17]:1
 [2] eval
   @ ./boot.jl:373 [inlined]
 [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base ./loading.jl:1196

Anonymous functions

function call_fn(f)
    f(3)
end
call_fn (generic function with 1 method)
call_fn(x -> x ^ 2)
9
call_fn(x -> x + 4)
7