From 1573d4c99be0702e6ec2b892eec874ed16f6c5dc Mon Sep 17 00:00:00 2001 From: Laurent Cheylus Date: Wed, 25 Jun 2025 13:41:32 +0200 Subject: [PATCH] docs: add a section for Lambda function expressions `f(|x,y|x+y)` (fix #23223) (#24789) --- doc/docs.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/doc/docs.md b/doc/docs.md index fa9a6bbf15..080d04782e 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -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. @@ -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 ~~epic flame wars~~ constructive criticism exchanges and design decisions. Join it, and learn more about languages, games, editors, people, Klingons, -Conway's law and the universe. +Conway's law and the universe. \ No newline at end of file