Created
May 10, 2017 04:51
-
-
Save omochi/e4f7c07a5948c66604a796e31241a48f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Consumer { | |
associatedtype Element | |
func consume(_ x: Element) | |
} | |
protocol Provider { | |
associatedtype Element | |
func provide() -> Element | |
} | |
func connect<C: Consumer, P: Provider>(_ p: P, _ c: C) where P.Element == C.Element { | |
c.consume(p.provide()) | |
} | |
struct IntConsumer : Consumer { | |
typealias Element = Int | |
func consume(_ x: Int) { | |
print("consume Int: \(x)") | |
} | |
} | |
struct IntProvider : Provider { | |
typealias Element = Int | |
func provide() -> Int { | |
return 333 | |
} | |
} | |
connect(IntProvider(), IntConsumer()) | |
enum IntOrString { | |
case int(Int) | |
case string(String) | |
static func lift(_ x: Int) -> IntOrString { | |
return .int(x) | |
} | |
static func lift(_ x: String) -> IntOrString { | |
return .string(x) | |
} | |
} | |
struct IntOrStringConsumer : Consumer { | |
typealias Element = IntOrString | |
func consume(_ x: IntOrString) { | |
switch x { | |
case let .int(x): | |
print("consume Int: \(x)") | |
case let .string(x): | |
print("consume String: \(x)") | |
} | |
} | |
} | |
func connect<C: Consumer, P: Provider>( | |
_ p: P, | |
_ c: C, | |
_ f: (P.Element) -> C.Element | |
){ | |
c.consume(f(p.provide())) | |
} | |
connect(IntProvider(), IntOrStringConsumer()) { .lift($0) } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment