Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

pine script - TradingView's Pinescript - why isn't recursion allowed?

The docs state:

Pine Scipt functions do not support recursion. It is not allowed for a function to call itself from within its own code.

Why is this the case?

question from:https://stackoverflow.com/questions/65888462/tradingviews-pinescript-why-isnt-recursion-allowed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because in Pine, in order to call a function, it must be completely defined in the code above the point you're calling it from. In a recursive function, you're trying to call that same function, before it's completely defined, so Pine doesn't "know" that function yet.

In the example below, function_a() can be called from within function_b(), because it's already defined when the compiler gets to function_b(), so it's "known" at that point.

However, function_c() cannot call function_d() because it's not defined yet at that point, causing the compiler to throw an error.

//@version=4
study(title = "Study", overlay=true)

function_a(n) => 2 * n
function_b(n) => 3 * function_a(n)
function_c(n) => 4 * function_d(n)
function_d(n) => 5 * n

plot(na)

The same applies to a recursive function, like the factorial calculation below.
The moment we're trying to call the factorial() function from within itself, the definition of that function isn't complete yet, so the function is "unknown" at that point in the code, causing the compiler to throw an error.

//@version=4
study(title = "Study", overlay=true)

factorial(n) => 
    if (n <= 1)
        1
    else
        n * factorial(n-1)

plot(na)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...