Skip to content
Bill Hails edited this page Nov 2, 2024 · 15 revisions

Lists are immutable. All the list operators make and return copies if necessary.

A list is written between [ and ] with commas as separators. For example:

[5 + 5, 12]; // [10, 12]

The empty list is written [] and pronounced "nil".

There are a few list operators, namely:

@ (cons)

Creates a new list by prepending its lhs to its rhs (which must be a list of the same type):

12 @ [13, 14];

is [12, 13, 14], but

true @ [13, 14]

is a type error: bool != int. See Typedef for ways to create lists of mixed type.

The name cons comes from Lisp where it stands for "construct". You can call it pair if you like.

@@ (append)

Creates a new list by making a copy of the lhs with the rhs appended:

[12, 13] @@ [14, 15]; // [12, 13, 14, 15]

@ and @@ are both right-associative.

prefix < (car)

Returns the first element of the list:

<[1, 2, 3]; // 1

prefix > (cdr)

Returns all but the first element of the list:

>[1, 2, 3]; // [2, 3]

It is a run-time error to take the head or tail of an empty list.

Again the names car and cdr are lifted directly from Lisp, They have an honourable history though their etymology is a bit bizarre. Anyway I'm sticking with them but you can call them head and tail if you prefer.

Given that lists are typed, these car and cdr operations are much less useful than they would be in a lisp where because they combine (<>> is "caddr" for example) they would be useful indeed. I may remove them later to re-use them elsewhere, maybe for binary tree walking if I introduce a standard tree type.

Summary

Just to be clear then, lists in F♮ are singly linked lists consisting of either a nil (empty) list or a cons of a value (or a pointer to a value) and a pointer to the next item on the list.

For example the list [1, 2, 3] is stored internally as something like:

flowchart LR
a(cons) --> b(cons)
b --> c(cons)
c --> nil
a --> one((1))
b --> two((2))
c --> three((3))
Loading

except that because simple numbers (excluding rationals and bigints) are scalar values they are inlined in the pair rather than being pointed at. The same applies to chars.

Next: Strings and Chars

Clone this wiki locally