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) * [Mutable arguments](#mutable-arguments)
* [Variable number of arguments](#variable-number-of-arguments) * [Variable number of arguments](#variable-number-of-arguments)
* [Anonymous & higher-order functions](#anonymous--higher-order-functions) * [Anonymous & higher-order functions](#anonymous--higher-order-functions)
* [Lambda expressions](#lambda-expressions)
* [Closures](#closures) * [Closures](#closures)
* [Parameter evaluation order](#parameter-evaluation-order) * [Parameter evaluation order](#parameter-evaluation-order)
* [References](#references) * [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 ### Closures
V supports closures too. V supports closures too.
@ -8331,4 +8354,4 @@ This is the place to be, to discuss the V language, learn about latest
developments, quickly get help with issues, witness/participate in developments, quickly get help with issues, witness/participate in
~~epic flame wars~~ constructive criticism exchanges and design decisions. ~~epic flame wars~~ constructive criticism exchanges and design decisions.
Join it, and learn more about languages, games, editors, people, Klingons, Join it, and learn more about languages, games, editors, people, Klingons,
Conway's law and the universe. Conway's law and the universe.