Define and Use a Function
So far, you’ve learned how to give names to values. Now it’s time to give names to ideas, specifically, ideas for how to compute something.
This step introduces functions, not as things that do work immediately, but as descriptions of how something could be computed later.
Describing a Computation
For example, here’s a simple idea:
To double a number, add it to itself.
Instead of writing x + x every time, we want to describe it once and give it a name.
In JavaScript, you’d write:
function double(x) {
return x + x;
}
Or in Python:
def double(x):
return x + x
In our language, the same idea looks like this:
["double", "=", ["lambda", "x", ["x", "+", "x"]]];
Reading it piece by piece:
"double"— the name"="— we’re defining it["lambda", "x", ...]— a function that takes one input calledx["x", "+", "x"]— the body: addxto itself
We now have a function, a named rule that tells us what to do with any input. When the evaluator sees a lambda, it produces a value: an object { param, body } that records the parameter name and the body expression. This value is what gets stored in the environment and later used when the function is called.
Using the Function
Once defined, you can use the function in expressions:
["double", 5]; // -> 10
["double", [3, "+", 2]]; // -> 10
["double", ["double", 3]]; // -> 12
Here’s how it works:
- The evaluator finds that
"double"is a function with a parameter"x"and a body["x", "+", "x"] - It binds the argument to the parameter name in the environment
- Then it evaluates the body, where lookups of that name now return the bound value
This is the same environment you’ve already been using: set stores a binding, get retrieves it. Calling a function just adds one more binding before evaluating the body.
Your Task
Your job is to complete the rule for "call". This is what happens when a function is applied to an input.
You will be given:
- the name of the parameter the function expects,
- the body expression that describes the function’s behavior,
- and the argument expression being passed in.
To apply the function, use the environment:
- First, evaluate the argument expression so it becomes a value.
- Then, bind the parameter name to that value in the environment.
- Finally, evaluate the body.
Write your rule where it says // set param in environment and // evaluate the body.