Created
January 12, 2022 09:40
-
-
Save VAndrJ/4ff58ae126238a5c9ffc88fd21120b07 to your computer and use it in GitHub Desktop.
Function composition custom operators
This file contains hidden or 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
infix operator |>: ForwardApplication | |
infix operator >>>: ForwardComposition | |
infix operator ~>: ForwardComposition | |
infix operator >=>: ForwardComposition | |
/// Function application | |
public func |> <A, R>(a: A, f: (A) -> R) -> R { | |
f(a) | |
} | |
/// Function composition | |
public func >>> <A, B, R>(f: @escaping (A) -> B, g: @escaping (B) -> R) -> ((A) -> R) { | |
{ a in g(f(a)) } | |
} | |
/// Asynchronous function composition | |
public func ~> <T, U>( | |
_ first: @escaping (@escaping (Result<T, Error>) -> Void) -> Void, | |
_ second: @escaping (T, @escaping (Result<U, Error>) -> Void) -> Void) -> (@escaping (Result<U, Error>) -> Void | |
) -> Void { | |
{ result in | |
first { firstResult in | |
switch firstResult { | |
case let .failure(error): | |
result(.failure(error)) | |
case let .success(data): | |
second(data) { secondResult in | |
switch secondResult { | |
case let .failure(error): | |
result(.failure(error)) | |
case let .success(data): | |
result(.success(data)) | |
} | |
} | |
} | |
} | |
} | |
} | |
/// Effectful function composition | |
public func >=> <A, B, R>(_ f: @escaping (A) -> B?, _ g: @escaping (B) -> R?) -> ((A) -> R?) { | |
{ a in f(a).flatMap { b in g(b) } } | |
} | |
precedencegroup ForwardApplication { | |
associativity: left | |
higherThan: AssignmentPrecedence | |
} | |
precedencegroup ForwardComposition { | |
associativity: left | |
higherThan: ForwardApplication | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment