erg/examples/record.er
2023-09-23 23:50:28 +09:00

35 lines
851 B
Python

# Record is a feature similar to object (literal notation) in JS
# `.` means the field is public
john = {
.name = "John Smith";
.age = !27
}
print! john.name
print! john.age
assert john.name == "John Smith"
assert john.age == 27
# john.age.update! old -> old + 1
# assert john.age == 28
# Record is not Dict, so `john["name"]` is invalid
# A record whose values are all types will also behave as a type
Person! = {
.name = Str;
.age = Nat!
}
print! Person!.name
assert Person!.name == Str
# assert john in Person!
for! {.x = 1; .y = 2}.as_dict().items(), ((k, v),) =>
# k: Str, v: Int
print! k, v
# {=} means the empty record (type), which is the subtype of all records
iterate_rec! r: {=} =
for! r.as_dict().items(), ((k, v),) =>
print! k, v
iterate_rec! {a = 1; b = 2}
iterate_rec! {a = 1; b = 1.2; c = "a"}