Functional programming asks (among other things): What if functions could also be used as values?
Lambda Calculs asks: What if functions were the only kind of value you could have? What if everything was functions?
For example, let's say we want to represent boolean logic using lambda calculus. Operators like AND, OR, NOT would of course be functions.
But so would the values TRUE and FALSE! They are functions defined in a very clever way, such that any valid boolean expression actually does evaluate to the correct TRUE or FALSE value/function/thing.
TRUE is defined as (λx. λy. x)
. This means that it takes one argument (x), then takes another argument(y), and returns the first argument.
FALSE is the opposite: it returns the second argument.
Lambda calculus is actually quite simple to evaluate. There are really only two things you can do:
-
Replace a symbol with its definition. For example:
TRUE THING_A THING_B
⟶
(λx. λy. x) THING_A THING_B
-
Apply a value to a lambda argument. You take the firsst thing after of a lambda expression, and then use it to replace the first lambda variable inside of that expression.
For example:
(λx. λy. x) THING_A THING_B
⟶
(λy. THING_A) THING_B
Yes, the function goes inside the parentheses,but the values for arguments go outside of them! It's a bit unusual, but it makes a lot of sense once you get used to it.
If you keep doing that in the right order to a well-formed expression, you should eventually arrive at the correct answer.
"Wait, what do you mean by the
right order?!" - you might be asking.
Well, if you get unlucky with your choice of order, it's possible to run into infinite expansion loops and never get anywhere useful.
For this reason, a common convention is to always replace or apply the
left-most thing you can do that operation to. And this
usually works out fine.
Try it out!
Enough words! Below are links to some interactive examples of using lambda calculus for simple boolean logic.
In these visualizations, the Replace step is done automatically for you.
You will have to trigger each Apply step by clicking on the value which should be applied to a lambda variable.
Not
And
Or
Left as a (paper-based) exercise for the user.
Can you figure out what OR should be, based on how NOT and AND work?