Write a reusable function that filters items above a threshold so I can call it from anywhere.

← Functions and Methods · Ref: Q1061

Define a named pure function with one parameter that returns Boolean. Then use it in any stream pipeline with 'filter by'.

  defines function
    isAboveThreshold() as pure
      -> price as Float
      <- rtn as Boolean?
      minimumPrice <- 50.0
      rtn: price > minimumPrice

Usage in a pipeline:

  cat prices | filter by isAboveThreshold | collect as List of Float

The function must:
- Take exactly one parameter (the stream item type)
- Return Boolean (true = keep, false = discard)
- Be marked 'as pure' for use in pipelines

For a configurable threshold, extract the threshold into a record and use a method instead. See Q1064 for that pattern.

See Q1034 for stream map examples. See Q1035 for filter and collect.

Example

defines module qa.functions.writereusablefilter

  defines function

    isAboveThreshold() as pure
      -> price as Float
      <- rtn as Boolean?

      minimumPrice <- 50.0
      rtn: price > minimumPrice

    formatPrice() as pure
      -> price as Float
      <- rtn as String: `Price: ${price}`

  defines program

    ReusableFilterDemo()
      stdout <- Stdout()

      prices <- [12.50, 75.00, 8.99, 120.00, 45.00, 89.99]

      //Use the reusable function in a pipeline
      expensive <- cat prices
        | filter by isAboveThreshold
        | collect as List of Float
      stdout.println(`Expensive: ${expensive}`)

      //Reuse the same function with different data
      otherPrices <- [200.0, 30.0, 55.0]
      otherExpensive <- cat otherPrices
        | filter by isAboveThreshold
        | collect as List of Float
      stdout.println(`Other expensive: ${otherExpensive}`)

      //Combine with map
      cat prices
        | filter by isAboveThreshold
        | map with formatPrice
        > stdout

Common mistakes

E01010 — EK9 has no lambda syntax. Define a named pure function that returns Boolean for use with 'filter by'.

Incorrect:

    isAboveThreshold = lambda price: price > 50

Correct:

    isAboveThreshold() as pure
      -> price as Float
      <- rtn as Boolean?
Other ways to ask this
  • Write a pure filter function I can reuse across my application
  • How do I write a function for use in a stream pipeline?
  • Create a named function I can pass to filter by

Coming from another language?

Java: Predicate<T> lambda. Python: lambda or def. EK9: named pure function with Boolean return.

Keywords: function, stream, filter, pipeline, coder, pure, reusable