I rewrote a recursive function that was overflowing the stack to use an accumulator, since I thought ML was optimizing this pattern. However, I'm still getting a stack overflow exception. Is there anything wrong with this function wrt tail call optimization?
xquery version "1.0-ml";
declare variable $BATCH-DURATION := xs:dayTimeDuration("P5D");
declare function local:start-times(
$datetime-start as xs:dateTime,
$datetime-end as xs:dateTime,
$acc as xs:dateTime*
) as xs:dateTime+
{
if (($datetime-end - $datetime-start) le $BATCH-DURATION) then $acc
else local:start-times($datetime-start + $BATCH-DURATION, $datetime-end, ($acc, $datetime-start))
};
local:start-times(xs:dateTime('1800-01-01T17:45:42'), xs:dateTime('2017-10-10T17:45:42'), ())[last()]
I believe the tail call optimization only works if the return value of the function is untyped.
That is, try:
declare function local:start-times(
$datetime-start as xs:dateTime,
$datetime-end as xs:dateTime,
$acc as xs:dateTime*
)
{
Hoping that helps.