Functions
Defining Functions
In Solstice, functions are a way to organise and reuse code. Here’s an example function:
def add(int a, int b) int {
return a + b
}
Here’s what each part is:
def: Means “define”. Tells Solstice we are defining a function.add: This is your function name! Choose something unique.(int a, int b): These are the arguments your function takes.- Enclose your argument type and name pairs in brackets.
- The first identifier should be a type (such as
int,string, etc), the second should be an identifer - After each type-name pair, add a comma unless you’ve got no more arguments to define
int: This is your return typereturn a + b: This is where your code goes for the function
Calling Functions
Call a function in Solstice like this:
myFunction(a, b, c)
where:
myFunctionis the name of your function(a, b, c)are the arguments you would like to pass to the function.- Enclose the arguments in parentheses (
( )) - Each argument should be seperated by a comma
- Solstice will type-check each argument to ensure it matches the function’s specified types
- Enclose the arguments in parentheses (
Closures and Scoping
Each function has an attached closure, which is the state captured at runtime when the function is defined. All variables in the closure can be accessed inside the function body, however the closure cannot be modified (meaning all variables captured remain consistent across function runs).
This behaviour ensures that functions are not affected by global state, and will always have reliable, consistent behaviour.
Additionally, all defined arguments are avaliable in scope.
x = 10
def myFunction() int {
// Here, x is avaliable, however if we modify it,
// our changes won't affect the external state, or
// the state of this function when it runs.
puts x
x = 5
return x
}
myFunction() // returns 5, prints 10
myFunction() // returns 5, prints 10
puts x // prints 10, x has not been modified by myFunction
The type of a function
If you’d like to accept a function as an argument, you need to specify it’s type signature. That can be done like this:
fun(int, string) bool
where:
funtells Solstice we’re writing a type signature for a function(int, string)is the list of argument types (names are not needed), seperated by commas, surrounded by bracketsboolis the return type
making this type represent a function which takes an int and a string, and returns a bool.