Using the contract annotation to perform mappings of record fields #1493
Replies: 1 comment 2 replies
-
This is partly intended and partly an accident. For contracts to be properly lazy they need to be able to return a new value. For example, imagine having to check some condition on all the fields of a very large record. We don't want this check to evaluate the record fully, since that could take a very long time, but instead defer the actual check to the place a field in the record is used. For this, we make would make a new record whose field values are the original record's values wrapped in the check. There's a worked example in the manual. The side effect of this design is that a contract can actually return arbitrary values, like you discovered. For a single contract application to a value that's not a big deal. But contracts attached to record fields are "sticky", the intention being that a contract attached to field encodes a property that this field must at all times satisfy, even after many merges. It can be very opaque when exactly such contracts end up being applied to a value. In particular, they can end up being applied multiple times. This means that you need to make sure that whatever the contract returns is also accepted as an input to the contract. That is, contracts should be idempotent to prevent surprises. You will typically see this most quickly when using record merging. Consider
You might reasonably expect this to evaluate to In summary, I don't recommend using the contract system in this way. A valid use case for the "mapping power" of contract could be a normalization step, like |
Beta Was this translation helpful? Give feedback.
-
While searching for a way to ergonomically update only select (nested) fields of a record, I found out, that contract annotations are able to change the values of fields in contracts, leading to this code:
This seems a bit hacky to me but it works so I'm happy. Is this intended behavior / a known pattern?
Beta Was this translation helpful? Give feedback.
All reactions