Tzopilotl
Docs
GitHub

Tzopilotl by Example

13. Lists and the Cons Operator

13.1 List Literals

-- Create a list with the List constructor
let xs = List(1, 2, 3);
xs println;             -- List(1, 2, 3)

-- Empty list with type annotation
let empty List<Int> = nil;
empty println;          -- List()

13.2 Cons Operator (::)

-- Prepend an element with ::
let xs = List(1, 2, 3);
let ys = 0 :: xs;
ys println;             -- List(0, 1, 2, 3)

-- Build a list from scratch with :: and nil
let zs = 1 :: 2 :: 3 :: nil;
zs println;             -- List(1, 2, 3)

13.3 Pattern Matching with Cons

let xs = List(1, 2, 3);

-- Match head :: tail
match (xs) {
    h :: t: {
        h println;      -- 1
        t println;      -- List(2, 3)
    }
    nil: "empty" println;
}

-- Nested cons pattern
match (xs) {
    a :: b :: rest: {
        a println;      -- 1
        b println;      -- 2
        rest println;   -- List(3)
    }
    _: "short" println;
}

13.4 Iterating over Lists

-- For loop over a list
let lst = List(1, 2, 3);
for (x : lst) {
    x println;
}
-- Output: 1 2 3

13.5 Infinite Lists with iter

-- iter(value, fn) returns an infinite list: value, fn(value), fn(fn(value)), ...

-- Powers of two
let powers = iter(1, fn(x Int) Int { x * 2 });
powers take(10) println;
-- List(1, 2, 4, 8, 16, 32, 64, 128, 256, 512)

-- Natural numbers
let nats = iter(0, fn(x Int) Int { x + 1 });
nats take(5) println;
-- List(0, 1, 2, 3, 4)

-- Works with any type
iter("a", fn(s String) String { s $ s }) take(4) println;
-- List(a, aa, aaaa, aaaaaaaa)