Last active
April 8, 2025 12:48
-
-
Save line-o/642012dc355701cb663c0cf8e2056510 to your computer and use it in GitHub Desktop.
This is an example to illustrate the usage of the context item `.` in functions in records that are annotated with `%method`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(:~ | |
: Example of context item in functions annotated with %method in a record | |
: The geom:vector has three methods that operate on the record instance | |
: ?dimension() can be thought of as a computed value | |
: ?fill($dimension) is a helper function that is then used in | |
: ?plus($other) adds another geom:vector to this instance | |
:) | |
declare record geom:vector( | |
values as xs:double+, | |
dimension as fn() as xs:positiveInteger := %method fn() { count(?values) }, | |
fill as fn($dimension as xs:positiveInteger) as geom:vector := %method fn ($dimension) { | |
let $current-dimension := ?dimension() | |
return | |
if ($current-dimension > $dimension) then error() | |
else if ($current-dimension = $dimension) then . | |
else map:put(., "values", ( ?values, $current-dimension to $dimension - 1 ! 0 )) | |
}, | |
plus as fn($other as geom:vector) as geom:vector := %method fn($other) { | |
let $max-dimension := math:max((?dimension(), $other?dimension())) | |
return map:put(., "values", for-each-pair( | |
?fill($max-dimension)?values, | |
$other?fill($max-dimension)?values, | |
op("+")) | |
} | |
); | |
geom:vector((-1, 1, 0)) | |
?plus(geom:vector((1, -1))) | |
?values | |
(: yields the vector sum | |
(0, 0, 0) | |
:) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment