Lesson 11 of 15
Built-in Functions
Adding Built-in Functions
Real languages come with built-in functions. Let's add three:
| Function | Behavior |
|---|---|
abs(x) | Absolute value |
max(a, b) | Larger of two values |
min(a, b) | Smaller of two values |
Parsing Function Calls
When we see an identifier followed by (, it's a function call:
parseFactor() {
if (this.peek().type === "IDENT") {
const name = this.advance().value;
if (this.peek().type === "LPAREN") {
this.advance(); // consume (
const args = [];
if (this.peek().type !== "RPAREN") {
args.push(this.parseExpr());
while (this.peek().type === "COMMA") {
this.advance();
args.push(this.parseExpr());
}
}
this.advance(); // consume )
return { type: "CallExpr", name, args };
}
return { type: "Identifier", name };
}
// ... numbers, parens
}
Evaluating Calls
if (node.type === "CallExpr") {
const args = node.args.map(a => evaluate(a, env));
if (node.name === "abs") return Math.abs(args[0]);
if (node.name === "max") return Math.max(args[0], args[1]);
if (node.name === "min") return Math.min(args[0], args[1]);
}
Your Task
Add support for abs, max, and min built-in functions. You will need a COMMA token type for argument separation.
Node.js loading...
Loading...
Click "Run" to execute your code.