ava/records.md

101 lines
1.9 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 is (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:
```
record Foo[A, B] is (x: A, y: B)
```
## Instantiating Records
```
record Foo is (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 is (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 is (x: String, y: Int32)
let foo := Foo("foo", 1)
let bar := foo.x
```
Note that because records are just tuples, tuple syntax continues to work:
```
let baz: Int32 := foo._2
```
## Tuple Interactions
Use the following record definition for this section:
```
record Foo is (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
```
## Destructuring Records
Records can be _destructured_ via [pattern matching](pattern-matching.md)
capabilities. This can take two possible forms.