Optional and defaulted fields
Relaxing the strict record builder, so a field can be set in any order or left unset.
Overview
Context-Generic Programming (CGP) assembles a struct generically by its field names, and
its core record builder is deliberately strict: a field is set once, and a
partial record becomes its struct only when every field
is present. That strictness catches a missing field at compile time, and it is too rigid for a
record whose fields arrive unpredictably or have sensible defaults. These traits, from
cgp-field-extra, relax it while reusing the same machinery underneath. Nothing here is in the
prelude. Import each from cgp::extra::field::impls.
The layer divides into entry points, the setter, the two endings, and the transform markers behind them.
The entry points produce an all-optional builder, whose every field is an Option.
HasOptionalBuilder starts one from nothing, and ToOptional
converts an existing builder into one.
SetOptional is the setter, which sets a field as many times as you like,
because an optional field's marker does not change when it is written.
The two endings are chosen at the finalize call rather than when the builder is made.
FinalizeOptional requires every field and reports a missing one, while
CanFinalizeWithDefault fills a missing field from Default.
CanBuildWithDefault chains a merge and a defaulted finalize into one call.
The transform markers carry the per-field conversions the endings run.
TransformMapDefault makes every field present, and
TransformOptional makes every field optional.
The ideas behind them
- Extensible records: partial records, and where relaxing presence fits.
An AI agent wrote this page using the CGP knowledge base. Its content was verified against the library's source. See How AI is used in this project.