LESSON 22 OF 52 · CHAPTER 03

Recursion

Recursive Fibonacci and mutually recursive even/odd tests

ORIGINAL SOURCE

02-recursion.srp

// Recursive frames have independent parameters and locals.
pure funcra fib(n: integer) -> integer
    needs n >= 0;
{
    if n <= 1 { return n; }
    return fib(n - 1) + fib(n - 2);
}

pure funcra even(n: integer) -> boolean {
    if n == 0 { return true; }
    return odd(n - 1);
}

pure funcra odd(n: integer) -> boolean {
    if n == 0 { return false; }
    return even(n - 1);
}

print(fib(10));
print(even(8), odd(8));
EXPECTED OUTPUT

stdout

Verified
55
true false

UNDERSTAND THE CODE

Explanation & practice

What this example teaches

Recursive Fibonacci and mutually recursive even/odd tests

Expected behavior

55, then true false

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.

रिकर्शन

fib(n) आधार स्थिति पर रुकता है; अन्यथा छोटी संख्याओं के साथ स्वयं को बुलाता है। even और odd परस्पर एक-दूसरे को बुलाते हैं। needs n >= 0 एक पूर्वशर्त है।

आउटपुट: fib(10) से 55, फिर even(8) और odd(8) से true false मिलता है।

अभ्यास: fib(3) के लिए आधार स्थितियों तक कॉल क्रम लिखें।

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

SOURCE-BACKED SELF-CHECK · स्रोत-आधारित अभ्यास

Quick checkpoint / त्वरित अभ्यास

What does fib(10) print in this recursive example?इस recursive उदाहरण में fib(10) क्या प्रिंट करता है?

Reveal the source-backed answer / सही उत्तर देखें

55 — The function returns n when n is at most 1 and otherwise adds fib(n - 1) and fib(n - 2); fib(10) is 55.55 — n का मान 1 या उससे कम होने पर फ़ंक्शन n लौटाता है; अन्यथा पिछले दो Fibonacci मान जोड़ता है। fib(10) = 55 है।

This question checks understanding of a recorded compiler output. It does not run Scarp in the browser. यह प्रश्न सत्यापित आउटपुट पर आधारित है; ब्राउज़र में Scarp नहीं चलता।

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/02-recursion.srp scarp exec examples/03-functions/02-recursion.srp

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

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