Created
February 13, 2019 02:13
-
-
Save darrarski/ce4cfbe972e68c2ce925f4d2e5af33ba to your computer and use it in GitHub Desktop.
Functional programming helpers for Swift
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
// swiftlint:disable identifier_name | |
// MARK: - ForwardApplication | |
precedencegroup ForwardApplication { | |
associativity: left | |
higherThan: AssignmentPrecedence | |
} | |
infix operator |>: ForwardApplication | |
public func |> <A, B>(x: A, f: (A) -> B) -> B { | |
return f(x) | |
} | |
public func |> <A>(x: inout A, f: (inout A) -> Void) -> A { | |
f(&x) | |
return x | |
} | |
public func |> <A: AnyObject>(x: A, f: (A) -> Void) -> A { | |
f(x) | |
return x | |
} | |
// MARK: - ForwardComposition | |
precedencegroup ForwardComposition { | |
associativity: left | |
higherThan: SingleTypeComposition | |
} | |
infix operator >>>: ForwardComposition | |
public func >>> <A, B, C>(f: @escaping (A) -> B, g: @escaping (B) -> C) -> (A) -> C { | |
return { g(f($0)) } | |
} | |
// MARK: - SingleTypeComposition | |
precedencegroup SingleTypeComposition { | |
associativity: right | |
higherThan: ForwardApplication | |
} | |
infix operator <>: SingleTypeComposition | |
public func <> <A>(f: @escaping (A) -> A, g: @escaping (A) -> A) -> (A) -> A { | |
return f >>> g | |
} | |
public func <> <A>(f: @escaping (inout A) -> Void, g: @escaping (inout A) -> Void) -> (inout A) -> Void { | |
return { a in | |
f(&a) | |
g(&a) | |
} | |
} | |
public func <> <A: AnyObject>(f: @escaping (A) -> Void, g: @escaping (A) -> Void) -> (A) -> Void { | |
return { a in | |
f(a) | |
g(a) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment