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)
- Preferably be marked 'as pure' (recommended; a non-pure function is also accepted by 'map with')

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

E50060 — String has no toUpperCase() method in EK9; the method is upperCase(). Write the transform as a named pure function and pass it to map with by name. See ek9 -h E50060 for details.

Incorrect:

<- rtn as String: name.toUpperCase()

Correct:

<- 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: coder, pipeline, simple, map, stream, function, transform