bow-swift / bow

🏹 Bow is a cross-platform library for Typed Functional Programming in Swift
https://bow-swift.io
Other
643 stars 32 forks source link

Question: Easier flatMap api for ReaderT? #658

Closed haifengkao closed 3 years ago

haifengkao commented 3 years ago

The flatMap provided by Bow is very verbose, e.g. KleisliPartial<ForArrayK, ENV>.flatMap It requires us to type the Reader's partial type.

Is there any easier flatMap api to use?

import Bow

typealias ENV = String
typealias Items = ReaderT<ForArrayK, ENV, Int>

func toArray(count: Int) -> Items {
    let array = [Int].init(repeating: count, count: count)
    return .liftF(ArrayK(array))
}

func combineArrayOfArray() -> Items {

    // arr1.run("") outputs: ArrayK(3, 3, 3)
    let arr1 = toArray(count: 3)

    // arr2^.run("") outputs: ArrayK(3, 3, 3, 3, 3, 3, 3, 3, 3)
    let arr2 = KleisliPartial<ForArrayK, ENV>.flatMap(arr1) { (count) -> KleisliOf<ForArrayK, ENV, Int> in
        toArray(count: count)
    }

    return arr2^
}
truizlop commented 3 years ago

You should be able to use:

arr1.flatmap { count in toArray(count: count) }^
haifengkao commented 3 years ago

cool. the intellisense doesn't show up flatMap, but it works. thanks