Functions
LIGO functions are the basic building block of contracts. For example, entrypoints are functions and each smart contract needs a main function that dispatches control to the entrypoints (it is not already the default entrypoint).
The semantics of function calls in LIGO is that of a copy of the arguments but also of the environment. In the case of JsLIGO, this means that any mutation (assignment) on variables outside the scope of the function will be lost when the function returns, just as the mutations inside the functions will be.
Declaring Functions
Functions in JsLIGO can be defined in two main ways: using the keyword
function
or const
(the keyword let
is defaulted to const
in
this instance). The latter manner is preferred when the function body
is an expression. For example, here is how you define a basic function
that sums two integers:
You can call the function add
defined above using the LIGO compiler
like this:
If the body contains statements instead of a single expression, you
would use a block and a return
statement:
although it is arguably more readable to use function
, like so:
Note that JsLIGO, like JavaScript, requires the return
keyword to indicate
what is being returned. If return
is not used, it will be the same as
return unit
.
By default, LIGO will warn about unused arguments inside
functions. In case we do not use an argument, its name should start with
_
to prevent warnings.
Anonymous functions (a.k.a. lambdas)
It is possible to define functions without assigning them a name. They are useful when you want to pass them as arguments, or assign them to a key in a record or a map.
Here is how to define an anonymous function:
You can check the value of a
defined above using the LIGO compiler
like this:
If the example above seems contrived, here is a more common design pattern for lambdas: to be used as parameters to functions. Consider the use case of having a list of integers and mapping the increment function to all its elements.
You can call the function incr_map
defined above using the LIGO compiler
like so:
Nested functions (also known as closures)
It is possible to define a functions inside another function. These functions have access to variables in the same scope.
Recursive functions
In JsLigo, recursive functions are defined and called using the same syntax as non-recursive functions.