Chapter 4: a precondition that fails, built
Chapter 4 ends Halve with a bug on purpose: a caller that hands halve an unset Integer. It compiles - the compiler cannot see the value is unset - and fails when it runs, at the require. The IDE writes the function's signature and the program's shell; you type the function's work and the buggy caller. To play it in the IDE: Help > Lessons > Getting Started with EK9…, or ek9 -ide -lesson book-halve-nothing.
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.broken defines function //The same halve as Halve.ek9, with its precondition. halve() as pure -> n as Integer <- result as Integer? require n? result: n / 2 defines program //A bug on purpose: this caller hands halve an unset Integer. Broken() stdout <- Stdout() stdout.println(`half is ${halve(Integer())}`) //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…
Broken is the program's name. Choose Preview.
The preview shows Broken about to be written. Choose Apply.
Select the Broken() line and, above it, type the comment the book puts there. Saves when typed.
Select the stub, from ready <- true down to its //AI line, and type Broken's body exactly as the chapter shows it. Saves when typed.
Step 3: Run it
Choose Run > Run Program…
The project's only program is already chosen. Choose Run.
The run fails with a Panic - Requirement failed: n? - and no half is printed: the precondition caught the unset Integer. Choose Close.
The result
HalveNothing.ek9 now reads exactly as chapter 4 of Getting Started with EK9 shows it, and the run stopped at the require: a precondition is a promise checked when the function is called, not when it is written.
Where this lesson comes from
- For AI assistants - the MCP tool
ek9_new_construct,ek9_add_program.
In the EK9 reference: Functions in EK9













