1
|
|
import Foundation
|
2
|
|
|
3
|
|
/// A Contravariant Functor is the dual of a Covariant Functor, usually referred to as just `Functor`. Whereas an intuition behind Covariant Functors is that they can be seen as containing or producing values, Contravariant Functors can be seen as consuming values.
|
4
|
|
public protocol Contravariant: Invariant {
|
5
|
|
/// Creates a new value transforming the type using the provided function, preserving the structure of the original type.
|
6
|
|
///
|
7
|
|
/// - Parameters:
|
8
|
|
/// - fa: Value to be transformed.
|
9
|
|
/// - f: Transforming function.
|
10
|
|
/// - Returns: The result of transforming the value type using the provided function, maintaining the structure of the original value.
|
11
|
|
static func contramap<A, B>(_ fa: Kind<Self, A>, _ f: @escaping (B) -> A) -> Kind<Self, B>
|
12
|
|
}
|
13
|
|
|
14
|
|
public extension Contravariant {
|
15
|
|
// Docs inherited from `Invariant`.
|
16
|
0
|
static func imap<A, B>(_ fa: Kind<Self, A>, _ f: @escaping (A) -> B, _ g: @escaping (B) -> A) -> Kind<Self, B> {
|
17
|
0
|
return contramap(fa, g)
|
18
|
|
}
|
19
|
|
|
20
|
|
/// Given a function, provides a new function lifted to the context type implementing this instance of `Contravariant`, but reversing the direction of the arrow.
|
21
|
|
///
|
22
|
|
/// - Parameter f: Function to be lifted.
|
23
|
|
/// - Returns: Function in the context implementing this instance.
|
24
|
0
|
static func contralift<A, B>(_ f: @escaping (A) -> B) -> (Kind<Self, B>) -> Kind<Self, A> {
|
25
|
0
|
return { fa in contramap(fa, f) }
|
26
|
|
}
|
27
|
|
}
|
28
|
|
|
29
|
|
// MARK: Syntax for Contravariant
|
30
|
|
|
31
|
|
public extension Kind where F: Contravariant {
|
32
|
|
/// Creates a new value transforming the type using the provided function, preserving the structure of the original type.
|
33
|
|
///
|
34
|
|
/// - Parameters:
|
35
|
|
/// - f: Transforming function.
|
36
|
|
/// - Returns: The result of transforming the value type using the provided function, maintaining the structure of the original value.
|
37
|
0
|
func contramap<B>(_ f : @escaping (B) -> A) -> Kind<F, B> {
|
38
|
0
|
return F.contramap(self, f)
|
39
|
|
}
|
40
|
|
|
41
|
|
/// Given a function, provides a new function lifted to the context type implementing this instance of `Contravariant`, but reversing the direction of the arrow.
|
42
|
|
///
|
43
|
|
/// - Parameter f: Function to be lifted.
|
44
|
|
/// - Returns: Function in the context implementing this instance.
|
45
|
0
|
static func contralift<B>(_ f : @escaping (A) -> B) -> (Kind<F, B>) -> Kind<F, A> {
|
46
|
0
|
return F.contralift(f)
|
47
|
|
}
|
48
|
|
}
|