Created
May 4, 2011 05:57
-
-
Save xquery/954816 to your computer and use it in GitHub Desktop.
Inline caching (memoization) for higher order xquery functions
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
xquery version "1.0-ml"; | |
(: xquery memoization example for use with MarkLogic :) | |
declare variable $cache := map:map(); | |
declare function local:factorial($n as xs:integer) as xs:integer { | |
if ($n < 0) then | |
(0) | |
else if ($n = 0) then | |
(1) | |
else | |
$n * local:factorial($n - 1) | |
}; | |
declare function local:memoize($func,$var){ | |
let $key := xdmp:md5(concat($func,string($var))) | |
return | |
if(map:get($cache,$key)) then | |
(map:get($cache,$key), xdmp:log('cache hit')) | |
else | |
let $result := xdmp:apply($func,$var) | |
return | |
(map:put($cache,$key,$result), $result) | |
}; | |
let $memoize := xdmp:function(xs:QName("local:memoize")) | |
let $factorial := xdmp:function(xs:QName("local:factorial")) | |
let $a:= xdmp:apply($memoize, $factorial, 20) | |
let $b:= xdmp:apply($memoize, $factorial, 20) | |
let $c:= xdmp:apply($memoize, $factorial, 20) | |
let $d:= xdmp:apply($memoize, $factorial, 20) | |
let $e:= xdmp:apply($memoize, $factorial, 20) | |
return | |
$a |
Does this work with marklogic without problems
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
neat. Makes me not feel so bad about using maps in functional programming. Is Marklogic's Xquery engine/compiler smart enough to know that its memorization?