Last active
March 21, 2018 21:18
-
-
Save akbsteam/3bf9bf13a29cbe6a215605648bff9cff to your computer and use it in GitHub Desktop.
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
| import Foundation | |
| import AppKit | |
| precedencegroup ForwardApplication | |
| { | |
| associativity: left | |
| higherThan: AssignmentPrecedence | |
| } | |
| precedencegroup ForwardComposition | |
| { | |
| associativity: left | |
| higherThan: ForwardApplication | |
| } | |
| infix operator |>: ForwardApplication | |
| infix operator >>>: ForwardComposition | |
| func |> <A, B>(a: A, f: (A) -> B) -> B | |
| { | |
| return f(a) | |
| } | |
| func >>> <A, B, C>(f: @escaping (A) -> B, | |
| g: @escaping (B) -> C) -> ((A) -> C) | |
| { | |
| return { a in | |
| a |> f |> g | |
| } | |
| } | |
| enum Fail: Error { | |
| case urlFromString | |
| case tryFail(Error) | |
| case imageFromData | |
| } | |
| enum Result<T> { | |
| case success(T) | |
| case failure(Fail) | |
| } | |
| let stringToURL: (String) -> URL? = { URL(string: $0) } | |
| let dataToImage: (Data) -> NSImage? = { NSImage(data: $0) } | |
| func rMap<T, U>(_ fnc: @escaping (T) -> Result<U>) -> (Result<T>) -> Result<U> | |
| { | |
| return { | |
| switch $0 { | |
| case .failure(let err): | |
| return Result.failure(err) | |
| case .success(let val): | |
| return fnc(val) | |
| } | |
| } | |
| } | |
| func rOptMap<T, U>(_ fnc: @escaping (T) -> U?, _ error: Fail) -> (Result<T>) -> Result<U> | |
| { | |
| return rMap { | |
| if let result = ($0 |> fnc) { return Result.success(result) } | |
| return Result.failure(error) | |
| } | |
| } | |
| func rTryMap<T, U>(_ fnc: @escaping (T) throws -> U) -> (Result<T>) -> Result<U> | |
| { | |
| return rMap { | |
| do { | |
| let value = try fnc($0) | |
| return Result.success(value) | |
| } catch let error { | |
| return Result.failure(.tryFail(error)) | |
| } | |
| } | |
| } | |
| let stringToImage = { Result.success($0) } | |
| >>> rOptMap(stringToURL, .urlFromString) | |
| >>> rTryMap({ try Data(contentsOf: $0) }) | |
| >>> rOptMap(dataToImage, .imageFromData) | |
| let result = "https://placebear.com/broken" |> stringToImage | |
| print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment