Pattern matching
Operations with records
Records and tuples


This article discusses a record data type.


Records are pretty similar to tuples, but provide an ability to access their elements by name. Records in Ela are effectively associative immutable arrays which elements can be accessed both by index and by name. One can use the following literal form to construct records:
r = {x = 1, y = 2}
It is possible to name record fields using a combination of symbols that is not valid for Ela identifier:
r = { "long field name" = 1, y = 2 }
Also if you assign record fields with values of variables Ela can infer field names like so (this feature is also known as record punning):
x = 1
y = 2
{x,y} //The result is: {x=1,y=2}
Records are always compared using structural equality. Also it is not possible to change elements of records or to add new elements. However you can "clone" existing records and create new records that "inherit" their attributes. This done using concatenation function ++:
r1 = {x=1,y=2}
r1 ++ {z=3} //The result is: {x=1,y=2,z=3}
Concatenation always produces a new record.

Pattern matching

You can pattern match records using a special "record" pattern:
{name} = {name="John Doe",age=31,sex="male"}
You don't have to list all of the record fields - just the fields that you want to bind to names or to check their values:
{age=31,sex} = {name="John Doe",age=31,sex="male"}

Operations with records

Ela comes with a standard library that includes a record module. This module provides additional operations with records.
Let's say that we have the following record:
rec = { name = "John Doe", age = 31 }
We need to reference a record module first:
open record
And now we add a new field to the record like so:
rec2 = addFields { sex = "male" } rec
The result is:
{name="John Doe",age=31,sex="male"}
This will produce a new record.
It is also possible to remove fields from the record (by also creating a new record) using a removeField function:
rec3 = removeFields "sex" rec2
rec3 //The result is: {name="John Doe",age=31}
It is also possible to change a field:
rec4 = changeField "age" 32 rec3
rec4 //The result is: {name="John Doe",age=32}
This will produce a new record.
And to list all the fields from the record:
fields rec4 //The result is: ["name","age"]
When you have a name of a field you can always obtain a value of this field using generic getField function from standard prelude like so:
"name" `getField` rec //The result is: "John Doe"

Records and tuples

Records in Ela are essentially tuples with "names" that are attached to each element of a tuple. As a result you can use records in all the situations where tuples are expected. For example, you can pattern match records like tuples:
(a,b,c) = {name="John Doe",age=31,sex="male"}
(a,b,c) //The result is: ("John Doe",31,"male")
Or access a record element by its index using indexing operator:
rec4:1 //The result is: 32