LearnDataIndexing and fields

Indexing and fields

Read a field or an ordered item.

Use field access when the value has names. Use index access when the value has order.

let point := { x := 3, y := 4 };
let values := [10, 20, 30];
let x := point.x;
let first := values.[0];
x + first;

point.x reads the x field. values.[0] reads the first item in an ordered value.

A field is like a named drawer. An index is like a numbered slot. Names are safer when the meaning matters.

Check what should happen when an index is outside the available items. Real programs meet empty lists.

Field access

Use a dot for named data.

let server := { host := "localhost", port := 8080 };
let host := server.host;
let port := server.port;

Field names carry meaning. Prefer fields when a reader should not need to remember a position.

Indexed access

Use .[index] for ordered data.

let ports := [3000, 8080, 8081];
let defaultPort := ports.[0];
let appPort := ports.[1];

Indexes are best when the order is the point of the data. If index 1 means "application port", a record field named appPort may be clearer.