Types read from text
A type with fields and a pattern can be made from text. The pattern's named groups fill the fields of the same name, and each one is converted to its field's type. fn inside a type adds a method, which sees the fields:
<import package="KScript.Math" />
<enum name="Unit" values="cm, in, mm" />
<type name="Dimensions" description="A size such as H4cmW12in: height 4 cm, width 12 inches." pattern="/^H(?<height>[\d.]+)(?<height_unit>cm|in|mm)W(?<width>[\d.]+)(?<width_unit>cm|in|mm)$/i">
<field name="height" type="number" />
<field name="height_unit" type="Unit" />
<field name="width" type="number" />
<field name="width_unit" type="Unit" />
<fn name="width_in" params="unit: Unit" value="@convert_length(.width, .width_unit, $unit)" />
</type>
<let name="size" type="Dimensions" value="H4cmW12in" />
<echo>{ $size.width } { $size.width_unit } is { $size->width_in(cm) } cm</echo>import KScript.Math
enum Unit { cm, in, mm }
/// A size such as H4cmW12in: height 4 cm, width 12 inches.
type Dimensions {
pattern: /^H(?<height>[\d.]+)(?<height_unit>cm|in|mm)W(?<width>[\d.]+)(?<width_unit>cm|in|mm)$/i
height: number
height_unit: Unit
width: number
width_unit: Unit
fn width_in(unit: Unit) => @convert_length(.width, .width_unit, $unit)
}
$size: Dimensions = H4cmW12in
echo "{ $size.width } { $size.width_unit } is { $size->width_in(cm) } cm"When the text needs more than a pattern, parse: gives an expression that returns a map of the fields. It sees the text as $value and, with a pattern, the match as $match.