[xquery-talk] Implementing algorithms involving state across iterations in XQuery
Leonard Wörteler
leo at woerteler.de
Thu Jan 2 15:25:46 PST 2014
Charles,
Am 02.01.2014 22:36, schrieb Charles Duffy:
> 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?
I think you are looking for `fn:fold-left(...)` and/or
`fn:fold-right(...)` [1]. They can be used to thread some kind of state
through while iterating over a sequence. `fn:fold-left($seq, $z, $f)`
behaves similar to the following imperative snippet:
> $accum <- $z;
> foreach($item in $seq) {
> $accum <- $f($accum, $item);
> }
> return $accum;
Your algorithm could be written like this (untested):
> fn:fold-left(
> $inputs,
> map:new(),
> function($already-seen, $element) {
> if(local:map-contains-prefix-of($already-seen, $element))
> then $already-seen
> else (
> let $result := expensive-operation($element)
> return map:new((
> $already-seen,
> map:entry(get-key($element), $result)
> ))
> )
> }
> )
Hope that helps,
Leo
[1] http://www.w3.org/TR/xpath-functions-30/#func-fold-left
More information about the talk
mailing list