3.8 Functions
A function is an object mapping a tuple of arguments to a return value.
3.8.1 Basic syntax
A block with definition, body and return
function f(x, y)
return x + y
end
1, 3) f(
When return is omited, the return value is the last evaluated expression
function f(x, y)
x + yend
1, 3) f(
A simpler approach for short functions
f(x, y) = x + y1, 3) f(
It is possible to use unicode names
γ(x, y) = x + y1, 3) γ(
Anonymous functions that are useful for functional programming
2 + 2x - 1, [1, 3, -1]) map(x -> x^
3.8.2 Return
We can define the output type of the function
function g(x, y)::Int8
return x * y
end
3, 2)) typeof(g(
It is a convention to return nothing when the function does not need to return a value
function printx(x)
"x = $x")
println(return nothing
end
10.0) printx(
Multiple values can be returned (tuple)
function maxmin(x, y)
return max(x, y), min(x, y)
end
2, 3.0)
maxmin(2, 3.0))
typeof(maxmin(2, 3.0) a, b = maxmin(
3.8.3 Varargs functions
Functions with a variable number of arguments
bar(a, b, x...) = (a, b, x)
1, 2)
bar(1, 2, 3)
bar(1, 2, 3, 4)
bar(
3, 4)
x = (1, 2, x...) # splat tuple or array appending ...
bar(3, 4]
x = [1, 2, x...) # splat tuple or array appending ... bar(
This also works for
3.8.4 Operators are functions
1 + 2 + 3
1, 2, 3)
+(1, 2, 3)
mysum = +; mysum(
1(x) = x^2
1, 2, 3]) f1.([
- Tuple
0xe01, 1 + 1, "hello", 'x')
x = (
typeof(x)
1, b = "me")
x = (a = x.a
- Multiple return values
function foo(a, b) a + b, a - b end foo(2, 3) x, y = foo(2, 3)
- Argument destructuring
minmax(x, y) = (y < x) ? (y, x) : (x, y) minmax(10, 2) minmax(2, 10)
range((min, max)) = max - min range(minmax(10, 2))
- Varargs functions
bar(a, b, x…) = (a, b, x) bar(1, 2) bar(1, 2, 3) bar(1, 2, 3, 4) typeof(bar(1, 2, 3, 4)[3])
x = (3, 4, 5) bar(1, x…) x = [3, 4, 5] bar(1, x…)
3.8.5 Optional arguments
3.8.6 Function composition and piping
3, 6)
(sqrt ∘ +)("this is julia"))
map(first ∘ reverse ∘ uppercase, split(
3, 6) |>
(
sum |>
sqrt
"a", "list", "of", "strings"] .|> [uppercase, reverse, titlecase, length] [