Functions
Edit on GitHubFunctions are essential to any language. They allow us to reuse code and solve complex problems.
Defining Functions
Defining a named function is similar to naming any other value in Grain.
A function can perform a series of actions. One thing to note about functions in Grain is that they always return the result of the final expression in the function body, without needing an explicit return
statement.
Functions as First Class Citizens
Since functions are just like any other values in Grain, they can be passed as arguments to other functions.
1 | let doMath = (fn, x, y) => fn(x, y) |
Multiple Return Values
You can return multiple values from functions using tuples.
1 | let translateCoordinates = (x, y) => { |
Recursive Functions
We can define recursive functions using the rec
keyword. Recursive functions are a key part of Grain, so remember to use let rec
when necessary!