build-a-programming-language / lesson-43.md
Lesson 43 · Data structures & builtins

Arrays

The first compound data structure is the array - an ordered list of values. Today you parse array literals and evaluate them, evaluating each element expression in order.

The goal

Parse and evaluate an array literal into an array object holding its evaluated elements.

Start here - the target
TO DO
Scenario: Evaluating an array literal
Giventhe source [1, 2 * 2, 3 + 3]
Whenthe evaluator evaluates the program
Thenthe result is an array object whose elements are 1, 4, 6
Andlen([1, 2, 3]) yields 3
Background

An array is an ordered list of values, written [a, b, c]. Parsing reuses the comma-separated-list logic from call arguments: register [ as a prefix parse function that reads element expressions until the closing ]. Evaluating the literal evaluates each element expression in order and collects the results into a runtime Array object.

Elements are arbitrary expressions, so [1, 2 * 2, 3 + 3] evaluates to [1, 4, 6]. Extend len to report an array’s element count - len([1,2,3]) is 3 - which shows why a shared builtin registry was worth building: one function now works across strings and arrays. Reading elements out by position comes in the next lesson.

Make it work
type ArrayLiteral struct { Elements []Expression } // AST node
type Array struct { Elements []Object } // runtime object
// parse '[' as a prefix parse fn: a comma-separated list until ']'
// eval: evaluate each element expression in order into the Array
// extend len to return the element count for an Array
CheckpointDONE
Array literals parse and evaluate, and len reports an array's length. Commit.