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
When return is omited, the return value is the last evaluated expression
A simpler approach for short functions
It is possible to use unicode names
Anonymous functions that are useful for functional programming
3.8.2 Return
We can define the output type of the function
It is a convention to return nothing when the function does not need to return a value
Multiple values can be returned (tuple)
3.8.3 Varargs functions
Functions with a variable number of arguments
bar(a, b, x...) = (a, b, x)
bar(1, 2)
bar(1, 2, 3)
bar(1, 2, 3, 4)
x = (3, 4)
bar(1, 2, x...) # splat tuple or array appending ...
x = [3, 4]
bar(1, 2, x...) # splat tuple or array appending ...
This also works for
3.8.4 Operators are functions
- Tuple
- 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…)