Language Expansion: Variables, Statements, Functions

Lesson, slides, and applied problem sets.

View Slides

Lesson

Language Expansion: Variables, Statements, Functions

Why this module exists

We now move from "just expressions" to a real program: statements, variables, functions, and control flow. The goal is to keep the language small but useful, while staying readable and open to future changes.

This module defines the v2 language spec used by the next problems.


1) Primitives (dynamic types)

The language is dynamically typed. Values carry their own type at runtime.

Primitives:

  • number: integer
  • bool: true / false
  • string: double-quoted text
  • nil: absence of a value

We do not type-check expressions at compile time. Runtime errors are OK and expected.


2) Variables

We support three declaration keywords:

  • let and var: mutable bindings
  • const: immutable bindings (must have an initializer)

Examples:

let x = 10;
var y;
const pi = 3;

Variables are block scoped. A new { ... } creates a new scope.


3) Statements

Supported statements:

  • Variable declarations
  • Assignment: name = expr;
  • Expression statements: expr;
  • if / else
  • while
  • return
  • Blocks { ... }

Example:

let total = 0;
while (total < 10) {
    total = total + 1;
}

4) Functions

Functions are declared with fn and called by name.

fn add(a, b) {
    return a + b;
}

let x = add(1, 2);

Functions are top-level declarations in this pack. They can access global variables, but we do not introduce closures yet.


5) Truthiness

For control flow, only false and nil are falsey. Everything else is truthy.


6) Readability first

This language is deliberately small. Every feature is meant to be readable and extendable later. If you want a different design (types, closures, pattern matching), the structure stays the same.


Module Items