12/01/2018, 3:54 PM
Hi guys, I've been thinking about my program's design and come up with an idea that it might be a good fit to use some FP structures. But I am not very experienced in that field so I thought that maybe you will be so kind and help me 🙂 My problem is following: I have some input from the user and a data class which wraps it with a meaningful type lets call it RawInput. This rawInput data class is a part of sealed class Input. Another variation of that sealed class is ParsedInput. Next I have a bunch of processors which take this RawInput and they return Input type so it can be RawInput or ParsedInput. Because the amount of processors may vary I have a processors dispatcher which takes all these processors and make them process RawInput until the type changes to parsedInput. This obviously can be replaced by Either, but that's the easy part 🙂 Even if a single processor can't handle the rawInput it can apply some transformations to it. So it is important to pass the result between different processors. To achieve that I wrote foldUntil function
Copy code
inline fun <T, R> Iterable<T>.foldUntil(initial: R, operation: (acc: R, T) -> R, until: (acc: R) -> Boolean): R {
    var accumulator = initial
    for (element in this) {
        if (!until(accumulator)) {
        accumulator = operation(accumulator, element)
    return accumulator
and I am using it like that:
Copy code
processors.foldUntil(rawInput, function={ acc, resolver -> processor.process(acc as RawInput) }, until={ acc -> acc is RawInput })
But I believe that leveraging FP structures it can be done better. Sorry for the long post.