Created
September 2, 2021 05:08
-
-
Save inamiy/aec4163ee1124eae456588a5fd4d3f16 to your computer and use it in GitHub Desktop.
Swift Async monad https://twitter.com/inamiy/status/1433228105728987140
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
/// `async` monad that wraps async function. | |
public struct Async<T> | |
{ | |
public let run: () async -> T | |
} | |
// MARK: - Functor | |
extension Async | |
{ | |
public func map<U>(_ f: @escaping (T) -> U) -> Async<U> | |
{ | |
Async<U> { | |
f(await run()) | |
} | |
} | |
} | |
// MARK: - Applicative | |
extension Async | |
{ | |
public func zipWith<U>(_ u: Async<U>) -> Async<(T, U)> | |
{ | |
Async<(T, U)> { | |
await (self.run(), u.run()) | |
} | |
} | |
public func apply<U>(_ f: Async<(T) -> U>) -> Async<U> | |
{ | |
zipWith(f).map { $1($0) } | |
} | |
} | |
// MARK: - Monad | |
extension Async | |
{ | |
public func flatMap<U>(_ f: @escaping (T) -> Async<U>) -> Async<U> | |
{ | |
Async<U> { | |
await f(await run()).run() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment