Sum a list of integers using join with an addition function.

← Streams and Pipelines · Ref: Q1139

join reduces a stream to a single value via a binary function:

  total <- cat [10, 20, 30] | join with addIntegers | collect as Integer

The binary function takes two items and returns one. See Q1137, Q1134.

Example

defines module qa.streams.streamjoinsplit

  defines function

    addIntegers() as pure
      ->
        a as Integer
        b as Integer
      <- rtn as Integer: a + b

    isEven() as pure
      -> item as Integer
      <- rtn as Boolean: item mod 2 == 0

  defines program

    StreamJoinSplitDemo()
      stdout <- Stdout()

      //Join (reduce) to sum
      total <- cat [10, 20, 30] | join with addIntegers | collect as Integer
      stdout.println(`Sum: ${total}`)

      //Split by predicate, then flatten
      stdout.println("Split by even:")
      cat [1, 2, 3, 4, 5, 6]
        | split with isEven
        | flatten
        > stdout
Other ways to ask this
  • I need to reduce a stream to a single value by adding all items together
  • In Java I'd use stream().reduce(). Write the EK9 join equivalent
  • Given [10, 20, 30], produce the sum using a stream join operation
  • Aggregate stream items into a single result using join with a binary function

Coming from another language?

Java: stream().reduce(Integer::sum). Python: functools.reduce(). Rust: .fold(). EK9: | join with fn | collect as T.

Keywords: aggregate, sum, split, reduce, binary function, join