Apply two transformations in sequence: double a number then add ten.
← Functions and Methods · Ref: Q1169
Chain map stages with separate pure functions:
cat items | map with doubleIt | map with addTen | collect as List of Integer
Each map stage applies a pure function that transforms one value to another. Chaining multiple map stages composes transformations naturally through the pipeline. See Q235 for stream operations. See Q596 for function basics.
Example
#!ek9 defines module qa.functionsandmethods.composefunctions defines function doubleIt() as pure -> num as Integer <- rtn as Integer: num * 2 addTen() as pure -> num as Integer <- rtn as Integer: num + 10 intToString() as pure -> num as Integer <- rtn as String: $num defines program ComposeFunctionsDemo() stdout <- Stdout() items <- [1, 2, 3, 4, 5] // Chain two transformations: double then add ten transformed <- cat items | map with doubleIt | map with addTen | collect as List of Integer stdout.println(`Doubled then plus ten: ${transformed}`) // Stream to stdout stdout.println("Streamed:") cat items | map with doubleIt | map with addTen | map with intToString > stdout
Common mistakes
E50060 — EK9 streams use 'cat ... | map with fn | collect as ...' pipe syntax, not Java-style '.stream().map().collect()' method chains. See ek9 -h E50060 for details.
Incorrect:
transformed <- items.stream().map(doubleIt).map(addTen).collect()
Correct:
transformed <- cat items | map with doubleIt | map with addTen | collect as List of Integer
Other ways to ask this
- Write code to chain two map stages in a stream pipeline
- I have a list of integers and need to apply two sequential transformations
- Given [1, 2, 3], double each value then add ten to each result
- In Java I'd use stream().map(x -> x * 2).map(x -> x + 10). Write the EK9 equivalent
Coming from another language?
Java: stream().map(x -> x * 2).map(x -> x + 10). Python: map(lambda x: x + 10, map(lambda x: x * 2, items)). Rust: iter().map(|x| x * 2).map(|x| x + 10). EK9: cat | map with fn1 | map with fn2.
Keywords: chain, compose, function, map, pipeline, sequence, stream, transform