1
import Foundation
2

3
/// A MonadReader is a `Monad` with capabilities to read values from a shared environment.
4
public protocol MonadReader: Monad {
5
    /// Type of the shared environment
6
    associatedtype D
7

8
    /// Retrieves the shared environment.
9
    ///
10
    /// - Returns: Shared environment.
11
    static func ask() -> Kind<Self, D>
12

13
    /// Executes a computation in a modified environment.
14
    ///
15
    /// - Parameters:
16
    ///   - fa: Computation to execute.
17
    ///   - f: Funtion to modify the environment.
18
    /// - Returns: Computation in the modified environment.
19
    static func local<A>(_ fa: Kind<Self, A>, _ f: @escaping (D) -> D) -> Kind<Self, A>
20
}
21

22
public extension MonadReader {
23
    /// Retrieves a function of the current environment.
24
    ///
25
    /// - Parameter f: Selector function to apply to the environment.
26
    /// - Returns: A value extracted from the environment, in the context implementing this instance.
27 0
    static func reader<A>(_ f: @escaping (D) -> A) -> Kind<Self, A> {
28 0
        return map(ask(), f)
29
    }
30
}
31

32
// MARK: Syntax for MonadReader
33

34
public extension Kind where F: MonadReader {
35
    /// Retrieves the shared environment.
36
    ///
37
    /// This is a convenience method to call `MonadReader.ask` as a static method of this type.
38
    ///
39
    /// - Returns: Shared environment.
40 0
    static func ask() -> Kind<F, F.D> {
41 0
        return F.ask()
42
    }
43

44
    /// Executes this computation in a modified environment.
45
    ///
46
    /// This is a convenience method to call `MonadReader.local` as an instance method of this type.
47
    ///
48
    /// - Parameters:
49
    ///   - f: Funtion to modify the environment.
50
    /// - Returns: Computation in the modified environment.
51 0
    func local(_ f: @escaping (F.D) -> F.D) -> Kind<F, A> {
52 0
        return F.local(self, f)
53
    }
54

55
    /// Retrieves a function of the current environment.
56
    ///
57
    /// This is a convenience method to call `MonadReader.reader` as a static method of this type.
58
    ///
59
    /// - Parameter f: Selector function to apply to the environment.
60
    /// - Returns: A value extracted from the environment, in the context implementing this instance.
61 0
    static func reader(_ f: @escaping (F.D) -> A) -> Kind<F, A> {
62 0
        return F.reader(f)
63
    }
64
}

Read our documentation on viewing source code .

Loading