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
|
2023-12-17 01:33:55 +00:00
|
|
|
let mut x = 20
|
2023-10-02 01:41:38 +00:00
|
|
|
|
2024-01-01 14:11:41 +00:00
|
|
|
let 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
|
2023-12-17 01:33:55 +00:00
|
|
|
let mut x = 20
|
2023-10-02 01:41:38 +00:00
|
|
|
|
2024-01-01 14:11:41 +00:00
|
|
|
let f = fun() clone(x) {
|
2023-10-02 01:41:38 +00:00
|
|
|
print(x)
|
|
|
|
}
|
|
|
|
|
|
|
|
f() // 20
|
|
|
|
|
|
|
|
x = 30
|
|
|
|
f() // 20
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
## Lambdas
|
|
|
|
|
|
|
|
|
|
|
|
```thp
|
|
|
|
numbers.map {
|
2024-01-01 14:11:41 +00:00
|
|
|
$0 * 2
|
2023-10-02 01:41:38 +00:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|