Lambda Functions
The term Lambda function or Lambda expression comes from Lambda Calculus. Introduced by Alonzo Church in the 1930's as a part of a study of the foundations of mathematics. Just like the Turing machine is a fundamental model for computation, Lambda Calculus provides a equivalent model for computation. This little comment is a glimpse into a very interesting world of formal analysis of mathematics and computation that I encourage you to explore this subject at your leisure.
Most of the functions that we have encountered so far have names. But are the names really important? Actually, names are important only if we want to reuse the functions in many places. Then, referring to them by their name is quite handy.
We use Lambda functions most often when:
- We would like to just create a function "right where we need it"
- We only plan to use the function once.
- The function is fairly simple
- We want to return a function from a function.
Usually we do this to pass/receive these functions to other functions that need them.
Here are a couple of examples of Lambda Functions:
import Graphics.Element exposing (..)
import List exposing (..)
main =
flow down [print " add an ! to Hello : " (\s -> s ++ "!" "hello")
,print "the square of the first 10 numbers : " (map (\n -> n*n) [1..10])
]
print message value = show (message ++ (toString value))
So what are we seeing? lambda functions look like:
\(parameters) -> code
. They start with a \
then a list of parameters the ->
and the code for the function.
An actual example of a Lambda function the computes the square of a number looks like this:
<function> : number -> number
\n -> n*n
Notice the signature <function> : number -> number
which does not have a name.
We are beginning to see this construction with slightly different syntax in many languages as these languages become more and more functional.
In the next section when we encounter higher order functions we are going to see the full power of using lambda functions.
Exercises
- Define an anonymous function and use it to double all the elements of a list.
- Look at what Lambda functions in another language looks like.