I need a simple one-off function to transform items in a stream pipeline.

← Functions and Methods · Ref: Q1062

Define a pure function that takes one parameter and returns the transformed value. Use it with 'map with' in a pipeline.

  defines function
    toUpperCase() as pure
      -> name as String
      <- rtn as String: name.upperCase()

Usage:

  cat names | map with toUpperCase > stdout

For a simple one-line transform, the function body can be on the return line:

    addPrefix() as pure
      -> name as String
      <- rtn as String: "Hello, " + name

The function must:
- Take exactly one parameter (the stream item type)
- Return the transformed type (can be different from input)
- Be marked 'as pure'

See Q1061 for filter functions. See Q1034 for chained transforms.

Example

defines module qa.functions.writepipelinefunction

  defines function

    toUpperCase() as pure
      -> name as String
      <- rtn as String: name.upperCase()

    addPrefix() as pure
      -> name as String
      <- rtn as String: "Hello, " + name

    extractLength() as pure
      -> name as String
      <- rtn as Integer: name.length()

  defines program

    PipelineFunctionDemo()
      stdout <- Stdout()

      names <- ["alice", "bob", "charlie"]

      //Simple transform
      cat names | map with toUpperCase > stdout

      //Chain two transforms
      cat names
        | map with toUpperCase
        | map with addPrefix
        > stdout

      //Transform to different type (String -> Integer)
      lengths <- cat names
        | map with extractLength
        | collect as List of Integer
      stdout.println(`Lengths: ${lengths}`)

Common mistakes

E01010 — EK9 has no inline lambdas. Define a named pure function and pass it to 'map with' by name.

Incorrect:

    cat names | map with (n -> n.upperCase())

Correct:

    toUpperCase() as pure
      -> name as String
      <- rtn as String: name.upperCase()
Other ways to ask this
  • Write a small function for use with map in a pipeline
  • How do I write a transform function for stream processing?
  • Create a function that converts each item in a stream

Coming from another language?

Java: Function<T,R> lambda. Python: lambda or def. EK9: named pure function with return type.

Keywords: function, stream, map, simple, pipeline, coder, transform