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:
- declare a named function;
- call a function with evaluated arguments;
- distinguish parameters from arguments;
- predict local scope and name lookup during a call;
- return a value to the caller;
- explain the default result when no explicit value is returned;
- design a small reusable function contract; and
- trace calls, local environments, and results.
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:
- Identify the function declaration.
- Evaluate argument expressions from the call site.
- Bind argument values to parameters by position.
- Create the call's local bindings.
- Execute statements in order.
- Stop at the first executed return, or at the end of the body.
- Replace the call expression conceptually with its result.
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
- Confusing parameters with arguments. Parameters appear in the declaration; arguments appear at the call site.
- Passing arguments in the wrong order. Positional binding makes order part of the contract.
- Forgetting to call the function. Referencing a function name is not the same as using parentheses to invoke it.
- Expecting local names to survive the call. Return the needed result instead.
- Writing code after an unconditional return. That code cannot execute.
- Omitting a return from a value-producing path. The caller may receive null unexpectedly.
- Mixing calculation and printing. A function that returns a value is usually more reusable than one that only prints it.
- Skipping boundary validation. Invalid values can make an otherwise correct formula misleading.
Guided practice
Complete these exercises before checking the suggested reasoning.
- Write a function named square that returns the product of one number with itself.
- Write a function named is_adult that returns whether an age is at least 18 and returns false for a negative age.
- Trace clamp(2 * 9, 5, 12). Record evaluated arguments, parameter bindings, executed branch, and result.
- Refactor two repeated subtotal calculations into one function and call it twice with different arguments.
- Explain why a temporary binding created inside a function should not be read after the call.
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
- Create is_valid_quantity(quantity). It returns true only when quantity is greater than zero.
- Create calculate_subtotal(unit_price, quantity). It returns null when either input is invalid; otherwise it returns their product.
- Create discount_rate(subtotal). It returns 0.10 for subtotals of at least 1000, 0.05 for subtotals of at least 500, and 0 otherwise.
- Create calculate_tax(amount, tax_rate). Reject negative amounts and rates outside the range 0 through 1.
- Create calculate_final_total(unit_price, quantity, tax_rate). It coordinates the other functions and returns null when a required result is invalid.
- Call the toolkit with at least four cases: ordinary, discounted, zero quantity, and invalid tax rate.
- Print a concise result for each case, but keep calculation functions free of printing side effects.
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
- Every function has one clear responsibility.
- Each call supplies arguments in the declared order.
- Every value-producing path returns explicitly.
- Invalid inputs produce a predictable result.
- Discount thresholds use first-match ordering.
- No calculation function depends on a local name from another call.
- Repeated formulas appear in only one function.
Extension. Add a shipping_cost(subtotal) function and include it in the final total. Document its threshold policy before implementing it.
Review questions
- What three main parts make up a function declaration?
- How does a parameter differ from an argument?
- When are argument expressions evaluated?
- Why does argument order matter in a positional call?
- What happens to a function's local bindings after the call finishes?
- What does return do to the remaining statements in the current call?
- What result should you expect when a function reaches its end without an explicit returned value?
- Why is returning a calculation often more reusable than printing it?
- Which contract details should be stated before implementing a boundary-sensitive function?
- How can early returns make validation logic easier to read?
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
- The function name communicates its purpose.
- The contract is visible and unambiguous.
- Invalid inputs are handled before the main calculation.
- Every reachable path returns a predictable value.
- The caller can reuse the result without depending on printed output.
- The test cases cover both policy branches and invalid boundaries.
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.