LESSON 23 OF 52 · CHAPTER 03

Function Contracts

Default and named arguments, needs and ensures contracts

ORIGINAL SOURCE

03-function-contracts.srp

// Optional arguments and executable contracts; no implicit numeric conversions.
pure funcra clipped(x: integer, lo: integer = 0, hi: integer = 10) -> integer
    needs lo <= hi;
    ensures result >= lo and result <= hi;
{
    if x < lo { return lo; }
    if x > hi { return hi; }
    return x;
}

pure funcra interval_end(start: integer, length: integer = 5) -> integer
    needs length >= 0;
    ensures result >= start;
{
    return start + length;
}

print(clipped(x: 15));
print(clipped(4, hi: 3, lo: 1));
print(interval_end(7), interval_end(length: 2, start: 10));
EXPECTED OUTPUT

stdout

Verified
10
3
12 12

UNDERSTAND THE CODE

Explanation & practice

What this example teaches

Default and named arguments, needs and ensures contracts

Expected behavior

10, 3, 12 12

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.

डिफ़ॉल्ट आर्गुमेंट और कॉन्ट्रैक्ट

clipped के lo और hi का डिफ़ॉल्ट मान होता है। x: 15 जैसे नामित आर्गुमेंट कॉल में दिए जाते हैं। needs पूर्वशर्त और ensures परिणाम की शर्त बताता है। ये कॉल वैध हैं।

आउटपुट: तीन पंक्तियाँ 10, 3 और 12 12 हैं।

अभ्यास: clipped(x: 15) सीमा के बाहर होने पर 10 क्यों देता है?

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 clipped(x: 15) return with the default maximum of 10?डिफ़ॉल्ट अधिकतम 10 होने पर clipped(x: 15) क्या लौटाता है?

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

10 — clipped uses defaults lo = 0 and hi = 10. Because x is greater than hi, it returns 10.10 — clipped में डिफ़ॉल्ट lo = 0 और hi = 10 हैं। x, hi से अधिक है, इसलिए फ़ंक्शन 10 लौटाता है।

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

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

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