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.
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 substitutes the argument into the body
- Then it evaluates the result
This is called the substitution model of evaluation: You replace the parameter with the argument, then evaluate 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, think in terms of substitution:
- First, connect the function’s parameter to the argument expression.
- Then, evaluate the body with that binding in place.
Write your rule where it says // your code here.