@@ -1975,13 +1975,47 @@ An example of a call expression:
1975
1975
let x: int = add(1, 2);
1976
1976
~~~~
1977
1977
1978
- ### Shared function expressions
1978
+ ### Lambda expressions
1979
1979
1980
- * TODO* .
1980
+ ~~~~~~~~ {.abnf .gram}
1981
+ ident_list : [ ident [ ',' ident ]* ] ? ;
1982
+ lambda_expr : '|' ident_list '| expr ;
1983
+ ~~~~~~~~
1981
1984
1982
- ### Unique function expressions
1985
+ A _ lambda expression_ (a.k.a. "anonymous function expression") defines a function and denotes it as a value,
1986
+ in a single expression.
1987
+ Lambda expressions are written by prepending a list of identifiers, surrounded by pipe symbols (` | ` ),
1988
+ to an expression.
1983
1989
1984
- * TODO* .
1990
+ A lambda expression denotes a function mapping parameters to the expression to the right of the ` ident_list ` .
1991
+ The identifiers in the ` ident_list ` are the parameters to the function, with types inferred from context.
1992
+
1993
+ Lambda expressions are most useful when passing functions as arguments to other functions,
1994
+ as an abbreviation for defining and capturing a separate fucntion.
1995
+
1996
+ Significantly, lambda expressions _ capture their environment_ ,
1997
+ which regular [ function definitions] ( #functions ) do not.
1998
+
1999
+ The exact type of capture depends on the [ function type] ( #function-types ) inferred for the lambda expression;
2000
+ in the simplest and least-expensive form, the environment is captured by reference,
2001
+ effectively borrowing pointers to all outer variables referenced inside the function.
2002
+ Other forms of capture include making copies of captured variables,
2003
+ and moving values from the environment into the lambda expression's captured environment.
2004
+
2005
+ An example of a lambda expression:
2006
+
2007
+ ~~~~
2008
+ fn ten_times(f: fn(int)) {
2009
+ let mut i = 0;
2010
+ while i < 10 {
2011
+ f(i);
2012
+ i += 1;
2013
+ }
2014
+ }
2015
+
2016
+ ten_times(|j| io::println(fmt!("hello, %d", j)));
2017
+
2018
+ ~~~~
1985
2019
1986
2020
### While loops
1987
2021
0 commit comments