Last active
March 23, 2018 16:21
-
-
Save akbsteam/25e1ae2f3e1086bf16091d072f83396b 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 UIKit | |
| 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<Value, E: Error> { | |
| case success(Value) | |
| case failure(Error) | |
| init(_ value: Value?, failWith: Error) | |
| { | |
| self = value.map(Result.success) ?? .failure(failWith) | |
| } | |
| init<U>(attempt f: @escaping (U) throws -> Value, with val: U) | |
| { | |
| do { | |
| self = .success(try f(val)) | |
| } catch let error { | |
| self = .failure(error) | |
| } | |
| } | |
| init(value: Value) { | |
| self = .success(value) | |
| } | |
| init(error: Error) { | |
| self = .failure(error) | |
| } | |
| } | |
| struct ResultMap | |
| { | |
| static func mapping<A, B, E>(_ fnc: @escaping (A) -> Result<B, E>) -> (Result<A, E>) -> Result<B, E> | |
| { | |
| return { | |
| switch $0 { | |
| case let .success(val): return fnc(val) | |
| case let .failure(err): return .failure(err) | |
| } | |
| } | |
| } | |
| static func optional<A, B, E>(_ fnc: @escaping (A) -> B?, failWith error: Fail) -> (Result<A, E>) -> Result<B, E> | |
| { | |
| return { Result(($0 |> fnc), failWith: error) } |> mapping | |
| } | |
| static func attempt<A, B, E>(_ fnc: @escaping (A) throws -> B) -> (Result<A, E>) -> Result<B, E> | |
| { | |
| return { Result(attempt: fnc, with: $0) } |> mapping | |
| } | |
| } | |
| let stringToResult = Result<String, Fail>.init(value:) | |
| let stringToURL = URL.init(string:) | |
| let dataToImage = NSImage.init(data:) | |
| let urlToDataThrowing = { try Data(contentsOf: $0) } | |
| let stringToImage = stringToResult | |
| >>> ResultMap.optional(stringToURL, failWith: .urlFromString) | |
| >>> ResultMap.attempt(urlToDataThrowing) | |
| >>> ResultMap.optional(dataToImage, failWith: .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