Function
A Function represents a callable block of code that returns a value, blank by default.
let empty_function be functionFunctions are called with do, with a sequence of parameters after with, following the Oxford comma rule.
let add be function with a, and b as
return a plus b
print do add with 1, and 2Details
For convenience:
- You may omit
dowhen using parameters. - You may also omit
with justwhen using exactly one parameter.
add with 1, and 2 # multiple parameter functions
print "hello world" # single parameter functionsNote: Functions are first-class. They can be assigned to variables and be passed around as values.
let execute be function with just other_function as
do other_function
let hello_world be function as
print "hello world"
execute hello_worldBlocks in Sparkle are also expressions, meaning that they evaluate to a single value, usually the last expression in the block, which is automatically returned.
let double be function with just x as
x * 2 # <- no return required
print double 12 # 24Function parameters can be made optional by assigning a default value using as.
Optional parameters may only be added after all required parameters.
let incremented be function with n, and amount as 1 as
return n plus amount
print incremented 100 # prints 101References
By default, parameters are passed by value, which means they're deep copied. To pass
values by reference, they must be marked explicitly.
let swap be function with a by reference, and b by reference as
let temp be b
update b to a
update a to tempThen, by reference must match in the function call.
let a be 1
let b be 2
swap a by reference, and b by referenceConstructor
Creates a new Function that's a copy of the given function.
Methods
Returns "function"
print "hello world"