Write a pure validation function that checks if an age is between 0 and 150.
← Functions and Methods · Ref: Q1168
Define a pure function with a Boolean return:
isValidAge() as pure -> age as Integer <- rtn as Boolean: age >= 0 and age <= 150
Pure functions cannot modify parameters or access external state. They are ideal for validation logic because they are testable, composable, and safe to use in stream pipelines. See Q596 for function vs method. See Q568 for pure basics.
Example
defines module qa.functionsandmethods.validation defines function isValidAge() as pure -> age as Integer <- rtn as Boolean? maxAge <- 150 rtn: age >= 0 and age <= maxAge isValidPercentage() as pure -> pct as Integer <- rtn as Boolean? maxPercent <- 100 rtn: pct >= 0 and pct <= maxPercent isNonBlank() as pure -> text as String <- rtn as Boolean: text? and text.length() > 0 defines program ValidationDemo() stdout <- Stdout() // Validate ages ages <- [25, -1, 0, 150, 151, 42] for age in ages if isValidAge(age) stdout.println(`Age ${age}: valid`) else stdout.println(`Age ${age}: invalid`) // Validate percentages scores <- [0, 50, 100, 101, -5] for score in scores if isValidPercentage(score) stdout.println(`Score ${score}: valid`) else stdout.println(`Score ${score}: invalid`) // Validate strings names <- ["Alice", "", "Bob"] for name in names if isNonBlank(name) stdout.println(`Name '${name}': valid`) else stdout.println(`Name '${name}': blank`)
Common mistakes
E01072 — EK9 has no return statement; assign the result to the declared return variable instead. See ek9 -h E01072 for details.
Incorrect:
return age >= 0 and age <= maxAge
Correct:
rtn: age >= 0 and age <= maxAge
Other ways to ask this
- Write code to validate a numeric range using a pure function
- I have an age value and need to verify it falls within a valid range
- Given an integer, produce a Boolean indicating whether it is a valid age
- In Java I'd write a static boolean isValidAge(int age). Write the EK9 equivalent
Coming from another language?
Java: static boolean isValidAge(int age) { return age >= 0 && age <= 150; }. Python: def is_valid_age(age): return 0 <= age <= 150. Rust: fn is_valid_age(age: i32) -> bool. EK9: isValidAge() as pure -> age as Integer <- rtn as Boolean.
Keywords: predicate, age, range, validation, pure, check, function, boolean