Skip to content
Function Declaration & Calls
step 1/3

Reading — step 1 of 3

Functions — Reusable Code

~2 min readControl Flow & Functions

Function Declaration & Calls

Functions are the primary abstraction mechanism in programming. They let you name a piece of code and call it with different arguments.

Declaration

fun greet(name) {
    print "Hello, " + name + "!";
}

The fun keyword declares a function with a name, parameter list, and body. Functions in our language are first-class values — they can be assigned to variables, passed as arguments, and returned from other functions.

Calls

greet("World");   // outputs: Hello, World!

A call expression evaluates the callee (the function), evaluates the arguments left-to-right, then executes the body with the arguments bound to the parameters.

Arity Checking

The number of arguments must match the number of parameters:

fun add(a, b) { return a + b; }
add(1);        // Error: Expected 2 arguments but got 1.
add(1, 2, 3); // Error: Expected 2 arguments but got 3.

How Functions Execute

When a function is called:

  1. Create a new environment enclosed by the function's defining environment (not the caller's — this is lexical scoping)
  2. Bind each argument to its corresponding parameter name in the new environment
  3. Execute the body in the new environment
callFunction(fn, arguments):
    env = new Environment(enclosing=fn.closure)
    for i, param in fn.params:
        env.define(param, arguments[i])
    executeBlock(fn.body, env)

Functions as Values

Functions are values, just like numbers and strings:

fun add(a, b) { return a + b; }
var op = add;
print op(1, 2);   // outputs: 3

This is a key design decision. In Crafting Interpreters, Nystrom models functions as objects that implement a Callable interface. Python does the same — functions are objects with a __call__ method.

Native Functions

Most languages provide built-in functions. We can add a clock() function that returns the current time — useful for benchmarking:

print clock();   // outputs: 1697234567.89

Native functions are implemented in the host language (Python, C, etc.) and injected into the global environment before the program runs.

Your Task

Implement function declaration, calls, arity checking, and first-class function values. Functions should create their own scope using lexical scoping rules.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…