Skip to content

Instantly share code, notes, and snippets.

@inamiy
Created September 2, 2021 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inamiy/aec4163ee1124eae456588a5fd4d3f16 to your computer and use it in GitHub Desktop.
Save inamiy/aec4163ee1124eae456588a5fd4d3f16 to your computer and use it in GitHub Desktop.
/// `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