Functions
A function returns different values depending on its input. In Gren, a function will always return the same result if provided the same input.
Here, sumOf
is the name of the function, while first
and second
are the inputs to the function. The return value of sumOf
is the last computed expression. In this case, the only expression is first + second
, the result of which becomes the returned value.
Functions can take an arbitrary number of arguments, but must return exactly one value.
Function arguments can be passed on multiple lines:
It looks kind of silly here, but it is helpful to know this when you’re reading code with longer arguments that may be formatted this way.
Function Pipelines
You can chain multiple function calls with parenthesis:
But you can make this more readable with the |>
operator:
|>
passes the value on the left as the last argument to the function on the right.
For example sumOf 1 2 |> multiply 3
is the same as multiply 3 (sumOf 1 2)
.
Anonymous Functions
You can create functions without giving them a name:
This is helpful when functions take another function as an argument:
The first parameter of Array.map
is a function that takes a value and returns a new value of the same type.
We’re creating those functions inline to build a function pipeline that results in [4, 6, 8]
.