Lambda expressions

Lambda expressions are used when we want to define a function inline without giving it any name.

The following example shows the lambda expression of go+ style, which is more compact and easy to understand.

func transform(a []float64, f func(float64) float64) []float64 { return [f(x) for x <- a] } y := transform([1, 2, 3], x => x * x) println y // [1 4 9] z := transform([-3, 1, -5], x => { if x < 0 { return -x } return x }) println z // [3 1 5]

If we want a lambda to be defined without being executed, we only omit its identifier. For example:

func returnLambda() func(string) { return func(msg string) { println msg } } consoleLog := returnLambda() consoleLog "Hello"

If we want the lambda to be defined and executed, we omit its identifier and add an argument list in parentheses after the body’s closing curly brace. For example:

func(msg string) { println msg }("Hello")

Next example: Recursion