Write an EK9 function that takes a list of integers and returns the sum of all positive values.

← Functions and Methods · Ref: Q999

Here is the function using a for loop with a guard:

The function declares <- rtn as Integer: 0 for the return value. It iterates the list, checks each number with a guard, and accumulates positive values with :=.

Alternatively, use a stream pipeline with a for-range expression:

  positiveSum <- for number in numbers
    <- rtn <- 0
    if number > 0
      rtn := rtn + number

Both approaches produce the same result. The loop version is clearer for accumulation. The stream approach would use cat | filter | collect with a custom accumulator.

Example

defines module qa.functionsandmethods.writefromspec

  defines function

    sumPositives() as pure
      -> numbers as List of Integer
      <- rtn as Integer: 0

      for number in numbers
        if number > 0
          rtn := rtn + number

    isPositive() as pure
      -> number as Integer
      <- rtn as Boolean?

      zeroThreshold <- 0
      rtn: number > zeroThreshold

  defines program

    WriteFunctionDemo()
      stdout <- Stdout()

      mixedNumbers <- [10, -5, 23, -8, 15, -3, 42, -1]

      positiveSum <- sumPositives(mixedNumbers)
      stdout.println(`Sum of positives: ${positiveSum}`)

      //Also show the positive numbers using a stream
      stdout.println("Positive numbers:")
      cat mixedNumbers
        | filter by isPositive
        > stdout

Common mistakes

E01072 — 'return' does not exist in EK9. Declare the return variable with '<- rtn as Integer: 0' and update it with ':=' as the function executes.

Incorrect:

      return 0

Correct:

      <- rtn as Integer: 0
Other ways to ask this
  • How do I write a function that processes a list and returns a result?
  • Show me an EK9 function that filters and accumulates values
  • Write a pure function that sums positive numbers from a list

Coming from another language?

EK9 functions declare return values with <-, not return statements. For accumulation, use a loop with := to update the return variable.

Keywords: write, sum, function, filter, implement, accumulate