<div dir="ltr">Howdy --<div><br></div><div>I'd like to implement an algorithm akin to that described by the following pseudocode in XQuery 3 (my implementation of choice is BaseX):</div><div><br></div><div><font size="1" face="courier new, monospace">declare variable $inputs external;</font></div>
<div><font size="1" face="courier new, monospace"><br></font></div><div><font size="1" face="courier new, monospace">declare function local:map-contains-prefix-of($map, $element) {</font></div><div><font size="1" face="courier new, monospace">  for $map-key in map:keys($map)</font></div>
<div><font size="1" face="courier new, monospace">    where fn:string-prefix($map-key, $element/key)</font></div><div><font size="1" face="courier new, monospace">    return map:get($map, $map-key)</font></div><div><font size="1" face="courier new, monospace">}</font></div>
<div><font size="1" face="courier new, monospace"><br></font></div><div><font size="1" face="courier new, monospace">declare function local:result-collection($inputs) {</font></div><div><font size="1" face="courier new, monospace">  let $already-seen := map:new()</font><font size="1" face="courier new, monospace"> </font><span style="font-family:'courier new',monospace;font-size:x-small">(: intended to be "updated" / shadowed later :)</span></div>
<div><font size="1" face="courier new, monospace">  for $element in $inputs</font></div><div><font size="1" face="courier new, monospace">    where not(local:map-contains-prefix-of($already-seen, $element))</font></div><div>
<font size="1" face="courier new, monospace">    let $result := expensive-operation($element)</font></div><div><font size="1" face="courier new, monospace">    let $already-seen := map:new(($already-seen, map:entry(get-key($element), $result))<br>
</font></div><div><font size="1" face="courier new, monospace">    return $already-seen</font></div><div><font size="1" face="courier new, monospace">}</font></div><div><font size="1" face="courier new, monospace"><br></font></div>
<div><font size="1" face="courier new, monospace">local:result-collections($inputs)[last()]</font></div><div><br></div><div>...to explain in prose:</div><div><ul><li>I have a sequence of inputs, and expect to generate a shorter sequence of outputs.</li>
<li>I have a call, expensive-operation(), which results in (1) the desired return value for a given input, and (2) information necessary and sufficient to identify which other input elements will have the same output relatively cheaply (in this example, done with a string comparison).</li>
<li>I'm trying to determine how to minimize the number of calls to expensive-operation() in an XQuery statement while still generating the desired output.</li></ul><div>While I know how to do this in a few other functional languages (for instance, in Clojure with its atoms), I'm a bit lost in XQuery. Could I ask for a bit of clue?</div>
</div><div><br></div><div>Thanks!</div></div>