PeaBox Lab › PeaLang › Learn › Chapter 4 › Lesson 1

Part I — Foundations · Chapter 4 · Lesson 1 of 5 · 8 min read

Lesson 1: Declaring and Calling Functions

Lesson level: Foundation

Purpose: Package repeatable behavior behind named interfaces with clear inputs, local state, and returned results.

Learning objectives

By the end of this lesson, you should be able to:

1. Why functions matter

A function gives a useful operation a name. Instead of copying the same calculation or validation wherever it is needed, you define the behavior once and call it from each use site. This reduces duplication, exposes intent, and creates a boundary that can be tested independently.

A good function answers three questions: What inputs does it accept? What result does it produce? What conditions must be true for the result to be meaningful? Together, those answers form the function's contract.

2. Declaring a function

A function declaration introduces a name, a parameter list, and a body. The following function calculates a subtotal:

Example 1 — A first function

function subtotal(price, quantity) { return price * quantity } let line_total = subtotal(12.5, 4) print(line_total)

The declaration binds the name subtotal to callable behavior. The names price and quantity are parameters: local names that receive values when the function is called. The statements between the braces are the function body.

Naming guidance. Prefer a short verb or verb phrase that states the function's responsibility, such as calculate_total, is_valid_code, or format_label. Avoid vague names such as do_it or process when a more specific name is available.

3. Calling a function

A call names a function and supplies argument expressions in parentheses. PeaLang evaluates those expressions, binds their values to the corresponding parameters, executes the body in a local function environment, and makes the returned value the result of the call expression.

Example 2 — Arguments are expressions

function rectangle_area(width, height) { return width * height } let base = 6 let area = rectangle_area(base + 2, 3 * 4) print(area)

The first argument evaluates to 8 and the second to 12 before the body uses them. Parameter order therefore matters: the first argument binds to width, and the second binds to height.

4. Local function scope

Parameters and bindings declared inside a function belong to that call's local scope. They can be used by the function body but are not available to unrelated code after the call finishes. A local binding can also hide an outer binding with the same name; choosing distinct names usually makes the code easier to trace.

Example 3 — Local bindings stay local

let tax_rate = 0.18 function add_tax(amount) { let tax = amount * tax_rate let total = amount + tax return total } print(add_tax(250))

The function reads the outer tax_rate, but amount, tax, and total are local to the call. Each new call receives a fresh set of parameter and local bindings.

5. Returning results

A return statement ends the current function call immediately. If it includes an expression, that expression is evaluated and delivered to the caller. Statements later in the function body are not executed on that path.

Example 4 — Early return for invalid input

function safe_discount(amount, rate) { if amount < 0 { return null } if rate < 0 or rate > 1 { return null } return amount * rate } print(safe_discount(800, 0.1)) print(safe_discount(800, 1.5))

The first call returns a discount value. The second returns null because the rate violates the function's accepted boundary.

If execution reaches the end of a function without returning an explicit value, the call produces the language's default no-value result, null. Use that behavior deliberately. For a value-producing function, an explicit return on every meaningful path is usually clearer.

6. Designing a reusable contract

A small function contract should identify accepted inputs, rejected inputs, the result, and observable side effects. Keep validation close to the boundary so the body can operate on trusted values.

Example 5 — Contract before implementation

# Contract: # - amount must be zero or greater # - percent must be between 0 and 100 # - returns the discounted amount, or null for invalid input function apply_discount(amount, percent) { if amount < 0 { return null } if percent < 0 or percent > 100 { return null } return amount - (amount * percent / 100) }

7. Trace a call step by step

Use the following trace whenever a call is unfamiliar:

Guided trace

function clamp(value, low, high) { if value < low { return low } if value > high { return high } return value } let adjusted = clamp(7 + 8, 0, 10)

The arguments evaluate to 15, 0, and 10. Those values bind to value, low, and high. The second condition is true, so the call returns 10 and adjusted receives that value.

Common mistakes

Guided practice

Complete these exercises before checking the suggested reasoning.

Hands-on lab: Build a pricing-functions toolkit

Scenario. A small ordering program repeats quantity checks, subtotal calculations, discounts, and tax calculations. Replace the repeated logic with focused functions.

Requirements

Starter structure

function is_valid_quantity(quantity) { # TODO: return a boolean } function calculate_subtotal(unit_price, quantity) { # TODO: validate and return a value } function discount_rate(subtotal) { # TODO: apply highest threshold first } function calculate_tax(amount, tax_rate) { # TODO: validate and calculate } function calculate_final_total(unit_price, quantity, tax_rate) { # TODO: coordinate the smaller functions }

Verification checklist

Extension. Add a shipping_cost(subtotal) function and include it in the final total. Document its threshold policy before implementing it.

Review questions

Applied challenge: Shipping quote function

Design a function named shipping_quote(weight, distance, express). The function must reject negative weight or distance, calculate a base charge from both values, add an express surcharge only when requested, and return the final quote. Before writing the body, state the accepted inputs, invalid-input result, calculation policy, and returned value.

Test the function with boundary values, an ordinary shipment, an express shipment, and at least two invalid inputs. For every test, trace the arguments, parameter bindings, executed branches, and returned result.

Success criteria

Lesson summary

Functions turn repeated behavior into named, reusable units. A declaration defines parameters and a body; a call evaluates arguments and binds their values in a fresh local environment. Return communicates a result and ends the current call. Reliable functions make their contracts explicit, validate boundaries, keep responsibilities focused, and produce predictable results for every meaningful path.

Next lesson: Parameters, Return Values, Defaults, and Reusable Contracts

Lesson status: Approved.

← Previous Next →