Function

A Function represents a callable block of code that returns a value, blank by default.

let empty_function be function

Functions 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 2

Details

For convenience:

  • You may omit do when using parameters.
  • You may also omit with just when using exactly one parameter.
add with 1, and 2   # multiple parameter functions
print "hello world" # single parameter functions

Note: 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_world

Blocks 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 # 24

Function 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 101

References

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 temp

Then, by reference must match in the function call.

let a be 1
let b be 2

swap a by reference, and b by reference

Constructor

Creates a new Function that's a copy of the given function.

Methods

Returns "function"

print "hello world"