LESSON 24 OF 52 · CHAPTER 03

Terminal Recursion

A direct self-return with an accumulator, default argument, and needs contract

ORIGINAL SOURCE

04-terminal-recursion.srp

// A direct self-return can reuse its execution frame.
pure funcra count(n: integer, total: integer = 0) -> integer
    needs n >= 0;
{
    if n == 0 { return total; }
    return count(n - 1, total + 1);
}
print(count(128));
EXPECTED OUTPUT

stdout

Verified
128

UNDERSTAND THE CODE

Explanation & practice

What this example teaches

A direct self-return with an accumulator, default argument, and needs contract

Expected behavior

128

Practice: Read the source before looking at the output. Predict the values and their order, then use the pinned compiler to execute this lesson and compare the exact fixture. Identify which operation produces the result.

अंतिम कॉल वाला रिकर्शन

count(n, total) में total एक accumulator है जो हर कॉल में एक बढ़ता है। जब n == 0, कुल मान लौटता है। अन्यथा फ़ंक्शन सीधे return count(n - 1, total + 1) लिखता है। इस प्रकार का प्रत्यक्ष self-return कम्पाइलर में कुछ स्थितियों में फ्रेम दोबारा इस्तेमाल कर सकता है, लेकिन हर तरह का रिकर्शन हमेशा अनुकूलित होगा, ऐसा दावा नहीं है।

आउटपुट: 128।

अभ्यास: count(3) के लिए n और total के क्रम को तालिका में लिखें।

Explanations are sourced from the project's English chapter guide and हिन्दी अध्याय. The Scarp program and output are unchanged.

TRY IT LOCALLY

Verify, then execute

Use the pinned compiler from the course root. Keep any imported _support files next to the source.

scarp verify examples/03-functions/04-terminal-recursion.srp scarp exec examples/03-functions/04-terminal-recursion.srp

The website does not run code. Read the CLI guide ↗

CHAPTER 03 · LAST LESSON

Ready for your next step? · आगे क्या सीखें?

This is the final example in this chapter. Try its verified coding lab before moving on. Your lesson progress changes only when you mark a lesson complete.

Pinned compiler: Scarp v0.0.6-alpha.3 · ceff07d9014f. No simulated output.