docs: add a section for Lambda function expressions f(|x,y|x+y) (fix #23223) (#24789)

This commit is contained in:
Laurent Cheylus 2025-06-25 13:41:32 +02:00 committed by GitHub
parent 8f17139126
commit 1573d4c99b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -120,6 +120,7 @@ by using any of the following commands in a terminal:
* [Mutable arguments](#mutable-arguments)
* [Variable number of arguments](#variable-number-of-arguments)
* [Anonymous & higher-order functions](#anonymous--higher-order-functions)
* [Lambda expressions](#lambda-expressions)
* [Closures](#closures)
* [Parameter evaluation order](#parameter-evaluation-order)
* [References](#references)
@ -3021,6 +3022,28 @@ fn main() {
}
```
### Lambda expressions
Lambda expressions in V are small anonymous functions, defined using
the `|variables| expression` syntax. Note: this syntax is valid only inside calls to higher
order functions.
Here are some examples:
```v
mut a := [1, 2, 3]
a.sort(|x, y| x > y) // sorts the array, defining the comparator with a lambda expression
println(a.map(|x| x * 10)) // prints [30, 20, 10]
```
```v
// Lambda function can be used as callback
fn f(cb fn (a int) int) int {
return cb(10)
}
println(f(|x| x + 4)) // prints 14
```
### Closures
V supports closures too.