LESSON 24 OF 52 · CHAPTER 03
Terminal Recursion
A direct self-return with an accumulator, default argument, and needs contract
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));
stdout
128
Write what you expect this program to print. Check prediction for a line-level hint without revealing the answer, or reveal the verified output when ready. This checks displayed text only; it does not run Scarp or save your input.
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.
LEARNING PROGRESS
Keep your place
Mark this lesson complete when you are ready.
Only saved in this browser. No account or tracking.
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.srpThe 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.