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

["Request"] or combinator for Prisms #601

Closed ferranpujolcamins closed 3 years ago

ferranpujolcamins commented 4 years ago

Description

An or combinator for prisms.

Sample usage

It's useful to create Prisms that focus on several cases of an enum:

enum Line: AutoPrism {
    case header(Header)
    case comment(Comment)
    case code(Substring)

    var commentOrCode: Prism<Line, Either<Comment, Substring>> {
        Line.prism(for: Line.comment).or(Line.prism(for: Line.code))
    }
}

Potential implementation

extension PPrism {
    func or<C, D>(_ other: PPrism<S, T, C, D>) -> PPrism<S, T, Either<A, C>, Either<B, D>> {
        PPrism<S, T, Either<A, C>, Either<B, D>>(
            getOrModify: { s in
                self.getOrModify(s)
                    .mapLeft { _ in other.getOrModify(s) }
                    .swap()
                    .sequence()
                    .map { $0^ }^
            },
            reverseGet: { $0.fold(self.reverseGet, other.reverseGet) }
        )
    }
}

Modules

Optics

Breaking changes

None

truizlop commented 4 years ago

Looks good to me, feel free to open a PR with it! Definitely interesting to add new combinators that enhance the API.