Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Function Definition

Named Functions

Define a named function with the following syntax:

def functionName(args) type {
    ...
}

where:

  • functionName is the name of the function.
    • If functionName is already defined as a function or other value, it will only be overwritten if the type does not change.
  • args is multiple comma-seperated pairs of:
    • a type identifier for the parameter, and
    • an identifier (representing the parameter name)
  • type is the type of value which the function will return
  • ... is the code inside the function (the function body).
    • The function body will have access to previously set variables through a closure. The closure is a copy of all variables in their current state at function definition time.
    • The function body will also have access to the parameters defined in args.

Example:

def add(int a, int b) int {
    return a + b
}

Anonymous/Lambda functions

Define a lambda function with the following syntax:

lambda(args) type {
    ...
}

where:

  • args is multiple comma-seperated pairs of:
    • a type identifier for the parameter, and
    • an identifier (representing the parameter name)
  • type is the type of value which the function will return
  • ... is the code inside the function (the function body).
    • The function body will have access to previously set variables through a closure. The closure is a copy of all variables in their current state at function definition time.
    • The function body will also have access to the parameters defined in args.

Example:

add = lambda(int a, int b) int {
    return a + b
}

Lambda functions are most useful when passed as arguments to other functions.