Created
June 12, 2015 12:33
-
-
Save lsharada/4df299e5c0010280819b to your computer and use it in GitHub Desktop.
memoization - a step ahead of recursion
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
http://docs.marklogic.com/guide/performance/perftune -- performance tuning | |
xquery version "1.0-ml"; | |
(: xquery memoization example for use with MarkLogic :) | |
declare variable $cache := map:map(); | |
declare function local:books-by-author($a as element(b:author)) | |
as element(b:title)* | |
{ | |
for $b in doc("books.xml")/b:bib/b:book | |
where some $ba in $b/b:author satisfies | |
($ba/b:last=$l and $ba/b:first=$f) | |
order by $b/b:title | |
return $b/b:title | |
} | |
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 $books-by-author := xdmp:function(xs:QName("local:books-by-author")) | |
let $f:= xdmp:apply($memoize, $books-by-author, "Bach") | |
return | |
$a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment