erg-lang / erg

A statically typed language compatible with Python
http://erg-lang.org
Apache License 2.0
2.7k stars 55 forks source link

RFC: `Record.replace` method #505

Open mtshiba opened 8 months ago

mtshiba commented 8 months ago

If you want to replace only one element in a record, you can do it like:

rec = { x = 1; y = 2; z = 3 }
assert { x = rec.x; y = rec.y; z = 2 } == { x = 1; y = 2; z = 2 }

This is tedious and requires changing the code every time other fields are added or removed. So, We propose to add a replace method to the record type.

rec = { x = 1; y = 2; z = 3 }
assert rec.replace({ z = 2 }) == { x = 1; y = 2; z = 2 }
assert rec.replace({ x = 2; z = 2 }) == { x = 2; y = 2; z = 2 }

The argument is a record containing the fields to be rewritten. If you provide a record containing a field that does not exist in self, a compilation error will occur.

Also, the replace method returns the same type of self. Therefore, all record field types given as an argument must match the field types of the original record.