Lambda expressions
Lambda expressions are used when there is a need for a local function that is only used once or so. Additionally, it is used for functions that are so simple that they usually don’t need a name - which is why lambda functions are sometimes referred to as anonymous functions.
The advantage of a lambda function is that we don’t have to create a name for it, it avoids the syntax of local, and it circumvents issues of lexical scoping.
For example:
(define (only-bigger threshold lon)
(local [(define (pred n))
(> n threshold)]
(filter pred lon)))Considering the above function (which is part of a larger program), we can see that the local function pred is really a one liner. Additionally, any name given to pred will still be less clear than (> n threshold).
To implement this as a lambda function, then, all we have to do is take eveything after the name of the local function, including the function body, and place it into a lambda function call:
(define (only-bigger threshold lon)
(filter (lambda (n) (> n threshold)) lon))The way to read this is that lambda replaces local but it tells the interpreter to not give the function a name. Thus, we say: create a nameless function with a parameter n that is passed into its body.
Full example
#;
(define (qsort lon)
(if (empty? lon)
empty
(local [(define p (first lon))
(define (<p? n) (< n p))
(define (>p? n) (> n p))]
(append (qsort (filter <p? lon))
(list p)
(qsort (filter >p? lon))))))
(define (qsort lon)
(if (empty? lon)
empty
(local [(define p (first lon))]
(append (qsort (filter (lambda (n) (< n p)) lon))
(list p)
(qsort (filter (lambda (n) (> n p)) lon))))))