1
import Foundation
2

3
/// A MonadError has the same capabilities as a `Monad` and an `ApplicativeError`.
4
public protocol MonadError: Monad, ApplicativeError {}
5

6
// MARK: Related functions
7

8
public extension MonadError {
9
    /// Checks if the value of a computation matches a predicate, raising an error if not.
10
    ///
11
    /// - Parameters:
12
    ///   - fa: A computation in the context implementing this instance.
13
    ///   - error: A function that produces an error of the type this instance is able to handle.
14
    ///   - predicate: A boolean predicate to test the value of the computation.
15
    /// - Returns: A value or an error in the context implementing this instance.
16 1
    static func ensure<A>(_ fa: Kind<Self, A>, _ error: @escaping () -> E, _ predicate: @escaping (A) -> Bool) -> Kind<Self, A> {
17 1
        return flatMap(fa, { a in
18 1
            predicate(a) ? pure(a) : raiseError(error())
19 1
        })
20
    }
21
}
22

23
// MARK: Syntax for MonadError
24

25
public extension Kind where F: MonadError {
26
    /// Checks if the value of this computation matches a predicate, raising an error if not.
27
    ///
28
    /// This is a convenience method to call `MonadError.ensure` as an instance method of this type.
29
    ///
30
    /// - Parameters:
31
    ///   - error: A function that produces an error of the type this instance is able to handle.
32
    ///   - predicate: A boolean predicate to test the value of the computation.
33
    /// - Returns: A value or an error in the context implementing this instance.
34 0
    func ensure(_ error: @escaping () -> F.E, _ predicate: @escaping (A) -> Bool) -> Kind<F, A> {
35 0
        return F.ensure(self, error, predicate)
36
    }
37
}

Read our documentation on viewing source code .

Loading