Chapter 4: a precondition, built
Chapter 4's Halve states a precondition: halve works only on an n that is set. The IDE writes the function's signature - and the stub already carries a require for each parameter - so what you type is the return's name and the work. To play it in the IDE: Help > Lessons > Getting Started with EK9…, or ek9 -ide -lesson book-halve.
What you'll build
The lesson builds this program from a file holding only its module line - the finished file, as the book prints it.
#!ek9 defines module functions.safe defines function //'require' states what must be true before the work runs — a precondition. halve() as pure -> n as Integer <- result as Integer? require n? result: n / 2 defines program Demo() -> n as Integer stdout <- Stdout() stdout.println(`half of ${n} is ${halve(n)}`) //EOF
Step 1: halve — a pure function
Choose Code > New Construct > Function…
halve is the function's name. Add n of type Integer as its parameter, set Returns to Integer and tick pure. Choose Preview.
The preview shows halve about to be written. Choose Apply.
Select the halve() as pure line and, above it, type the comment the book puts there. Saves when typed.
Select the stub, from <- rtn as Integer? down to its //AI line, and type halve's own return and work, as the book writes them. Saves when typed.
Step 2: The program
Choose Code > New Construct > Program…
Demo is the program's name. Add one parameter, n of type Integer. Choose Preview.
The preview shows Demo about to be written. Choose Apply.
Select the Demo() line and, above it, type the blank line the book opens the program with. Saves when typed.
Select the stub, from require n? down to its //AI line, and type Demo's body exactly as the chapter shows it. Saves when typed.
Step 3: Run it
Choose Run > Run Program…
Type 10 into Arguments (space-separated), then choose Run.
half of 10 is 5. Choose Close.
The result
Halve.ek9 now reads exactly as chapter 4 of Getting Started with EK9 shows it: a pure function whose require n? is checked before result is assigned.
Where this lesson comes from
- For AI assistants - the MCP tool
ek9_new_construct,ek9_add_program.
In the EK9 reference: Functions in EK9














