ava/records.md

119 lines
2.2 KiB
Markdown

# Records
Records may be defined. Each record contains one or more named fields. Note that
records are just [tuples](tuples.md) 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](#anonymous-records)
- [Generic Records](#generic-records)
- [Instantiating Records](#instantiating-records)
- [Copying Data](#copying-data)
- [Accessing Record Data](#accessing-record-data)
- [Tuple Interactions](#tuple-interactions)
- [Destructuring Records](#destructuring-records)
## 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 by extracting the tuple metadata from the record.
```
let foo := Foo("foo", 1)
let bar: (String, Int32) := @foo.tuple
```
TODO: Metdata is up in the air.
Records respect the tuple size metadata.
```
let size := @foo.size
```
Records provide field metadata.
```
let desc: RecordDescription := @foo.description
```
## Destructuring Records
Records can be _destructured_ via [pattern matching](pattern-matching.md)
capabilities.