How do I write a pure function in EK9 that takes parameters and returns a result?
← Functions and Methods · Ref: Q873
Functions use '->' for input parameters and '<-' for the return value. Mark functions 'as pure' when they have no side effects — pure functions only compute from their inputs.
The return variable is declared on the '<-' line and automatically returned. EK9 has no 'return' statement — the compiler ensures all paths initialise the return variable.
See Q49 for function basics. See Q560 for purity contracts. Use 'ek9 -h function' for syntax.
Example
defines module qa.functions.pure.basics defines constant ADULT_AGE <- 18 defines function calculateArea() as pure -> width as Float height as Float <- rtn as Float: width * height isAdult() as pure -> age as Integer <- rtn as Boolean: age >= ADULT_AGE formatGreeting() as pure -> personName as String <- rtn as String: `Hello, ${personName}!` defines program FunctionDemo() stdout <- Stdout() area <- calculateArea(5.0, 3.0) stdout.println(`Area: ${area}`) stdout.println(`Adult: ${isAdult(21)}`) stdout.println(formatGreeting("Steve"))
Other ways to ask this
- Show me a function with input and output in EK9
- What does 'as pure' mean on a function?
- EK9 function with parameters and return value
Coming from another language?
Java: methods with return type. Python: def with return. Rust: fn with ->. EK9: '<-' declares return, 'as pure' enforces no side effects.
Keywords: function, output, side-effect, return, input, pure, parameter