ava/notes/records.md

2.1 KiB

Records

Records may be defined. Each record contains one or more named fields. Note that records are just tuples with named fields. In many ways, the two can be interchanged.

record Foo(x: String, y: Int32)

Record fields are both ordered and named.

Anonymous Records

Records do not need to be named.

#(x: String, y: String, z: String)

Generic Records

Records may have generically typed data, and accept a type constructor:

given A, B
record Foo(x: A, y: B)

Instantiating Records

record Foo (x: String, y: Int32)

let foo1 := Foo("foo", 1)
let foo2 := Foo(
    x := "foo",
    y := 1
)

Copying Data

Copy syntax allows any record to be duplicated, with any fields explicitly overridden by some value:

record Foo(x: String, y: Int32)

let foo := Foo("foo", 1)
let bar := copy foo
let baz := copy foo #(y := 2)

Accessing Record Data

The . operator is used to access individual fields on a record.

record Foo(x: String, y: Int32)

let foo := Foo("foo", 1)
let bar := foo.x

Tuple syntax is not supported on records.

Tuple Interactions

Use the following record definition for this section:

record Foo(x: String, y: Int32)

Tuples can be assigned from records.

let foo := Foo("foo", 1)
let some_tuple: #(String, Int32) := foo

Records can be assigned from tuples.

let some_tuple := #("foo", 1)
let foo: Foo := some_tuple

Records can be cast to tuples if the types/ordering are identical.

let foo := Foo("foo", 1)
let bar: #(String, Int32) := foo

Destructuring Records

Records can be destructured via pattern matching capabilities.

record Foo(x: String, y: Int32)

let foo := Foo("foo", 1)

match foo
    case "foo" _ => "bar"
    case _ 2 => "baz"
    case _ _ => "legume"
end match