androidengineers.Book a session

Functional Programming

Practice: FP Challenges

exercise55 minMedium

Write a reusable normalization pipeline

Build a function accepting text transformations and applying them in order. Keep transformations pure so the same input and same pipeline produce the same result.

fun pipeline(vararg steps: (String) -> String): (String) -> String =
    { input -> steps.fold(input) { value, step -> step(value) } }

fun main() {
    val normalize = pipeline({ it.trim() }, { it.lowercase() }, { it.replace(" ", "-") })
    check(normalize(" Kotlin Basics ") == "kotlin-basics")
}

The fold begins with the original input. An empty pipeline should therefore return its input unchanged. The order is part of the contract and should not be rearranged for perceived efficiency without checking semantics.

Acceptance checks

Test an empty pipeline, one step, repeated whitespace, and two deliberately noncommuting steps. Add a validator as a separate operation instead of turning a failed validation into a fabricated successful string.

Extension: make the pipeline generic for transformations of one type. Explain why composition where input and output types differ requires a different type signature than a vararg of identical transformations.

Reference: Higher-order functions

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Practice: FP Challenges | Kotlin Core Programming | Android Engineers