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)
- Preferably be marked 'as pure' (recommended; a non-pure function is also accepted by 'filter by')
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
E11064 — A bare literal inside a comparison is a magic literal. Give the threshold a meaningful name (minimumPrice) and compare against the name. See ek9 -h E11064 for details.
Incorrect:
rtn: price > 50.0
Correct:
minimumPrice <- 50.0 rtn: price > minimumPrice
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: coder, pipeline, filter, stream, function, reusable, pure