thp-web/md/learn/functions/lambdas.md

82 lines
906 B
Markdown
Raw Normal View History

2023-10-02 01:41:38 +00:00
# Lambdas / Anonymous functions
## Anonymous function
```thp
fun(Int x, Int y) -> Int {
x + y
}
numbers.map(fun(x) {
x * 2
})
```
## Closure types
By default closures **always** capture variables as **references**.
```thp
2024-02-20 10:53:38 +00:00
var x = 20
2023-10-02 01:41:38 +00:00
2024-02-20 10:17:21 +00:00
val f = fun() {
2023-10-02 01:41:38 +00:00
print(x)
}
f() // 20
x = 30
f() // 30
```
You can force a closure to capture variables by value.
```thp
fun(parameters) clone(variables) {
// code
}
```
```thp
2024-02-20 10:53:38 +00:00
var x = 20
2023-10-02 01:41:38 +00:00
2024-02-20 10:17:21 +00:00
val f = fun() clone(x) {
2023-10-02 01:41:38 +00:00
print(x)
}
f() // 20
x = 30
f() // 20
```
## Lambdas
2024-03-13 17:16:29 +00:00
Lambdas are a short form of anonymous functions. They are declared with `#{}`.
Inside the lambda you can access the parameters as `$1`, `$2`, etc.
Finally, lambdas be written outside of the parenthesis of function calls.
2023-10-02 01:41:38 +00:00
```thp
2024-03-13 17:16:29 +00:00
numbers.map() #{
$1 * 2
2023-10-02 01:41:38 +00:00
}
2024-03-13 17:16:29 +00:00
// the above lambda is equivalent to:
numbers.map(fun(param1) {
$1 * 2
})
2023-10-02 01:41:38 +00:00
```