A Lambda represents a way of defining a simple method model. A lambda is an expression, and can appear anywhere an expression can appear.
Most simply, a lambda can be used to create a method as follows:
<assign increment = #lambda(x) x + 1> <p>Next value is: ${increment(10)}</p>
Lambdas can also be used to create and pass anonymous methods into other method calls, as follows:
<assign list = [ 1, 2, 3, 4 ,5 ]> <assign sum = methods.reduce( list, #lambda(x, y) x + y )> <p>Sum is: ${sum}.</p>
Lambdas can be used to create closures. A closure can reference template model variables from the scope in which the lambda was created. For example:
<assign list = [ "one", "two", "three", "four" ,"five" ]> <assign filtered = methods.filter( list, #lambda(x) methods.match( "m/o/", x ))>
In the example above, the lambda refers to the methods.match
method from the scope in which the lambda was created.
Lambdas are typically used in conjunction with a functional programming style.
The filter
, map
, and reduce
methods
of the freemarker.ext.misc
package are common examples of
functional programming style. These methods are commonly called high-order functions.
See the JavaDoc for more details
of these methods.
Previous: Variable Escaping | Next: Models Introduction |