How to Use Fold Statement Index in Function Call

The fold manual gives an example:

input price = close;
input length = 9;
plot SMA = (fold n = 0 to length with s do s + getValue(price, n, length - 1)) / lenth;

This effectively calls a function iteratively like in a for loop body.

When I use this statement to call my own function as follows, then it breaks because the loop index variable is not recognized as a variable that can be passed to my function:

script getItem{ 
    input index = 0;
    plot output = index * index;
}
script test{
    def total = fold index = 0 to 10 with accumulator = 0 do
    accumulator + getItem(index);########## Error: No such variable: index
}

2 Answers

It is a known bug / limitation. Has been acknowledged without a time line for a fix. No workaround available.

Have you tried adding a small remainder to your defined variable within the fold and then pass that variable? You can strip the integer value and then use the remainder as your counter value. I've been playing around with somethin similar but it isn't working (yet). Here's an example:

script TailOverlap{
input i = 0;
def ii = (Round(i, 1) - i) * 1000;
... more stuff
plot result = result;
};

def _S = ( 
fold i = displace to period
with c = 0
do if              
    TailOverlap(i = _S)  #send cur val of _S to script    
then _S[1] + 1.0001      #increment variable and counter
else _S[1] + 0.0001      #increment the counter only
);

I'm going to continue playing around with this. If I get it to work I'll post the final solution. If you're able to get work this (or have discovered another solution) please do post it here so I know.

Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest