Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- open class Function <I, R, SomeError: Error>: Identifiable {
- struct Hash<Number: BinaryInteger>: Hashable {
- static func == (
- lhs: Function<I, R, SomeError>.Hash<Number>,
- rhs: Function<I, R, SomeError>.Hash<Number>
- ) -> Bool? {
- if lhs.hashValue == rhs.hashValue {
- return true
- } else {
- return false
- }
- return nil
- }
- //this hash must be persistent across launches
- private let seed: Int32 = 0b10101100110101
- public var hashValue: Number {
- let allNumericMetatypes: [Any.Type] = [
- Int8.self, Int16.self,
- Int32.self, Int64.self
- ]
- let number: Number
- for type in allNumericMetatypes {
- let val = MemoryLayout.size(ofValue: fn)
- if val <= type.max {
- number = type.init(exactly: val)
- }
- }
- return number * Number(seed) * 8
- }
- }
- internal let fn: (I) throws -> R
- public init(_ fn: @escaping (I) throws -> R) {
- self.fn = fn
- }
- open func invoke(_ arg: I) -> Result<R, SomeError> {
- do {
- return .success(try fn(arg))
- } catch let error {
- return .failure(error as! SomeError)
- }
- }
- open func invoke_thehard_way(_ arg: I) -> R {
- try! fn(arg)
- }
- }
- infix operator << : MultiplicationPrecedence
- infix operator <<? : MultiplicationPrecedence
- func << <I, R, Error>(lhs: Function<I, R, Error>, rhs: I) -> Result<R, Error> {
- lhs.invoke(rhs)
- }
- public func << <I, R>(lhs: Function<I, R, Never>, rhs: I) -> R {
- lhs.invoke_thehard_way(rhs)
- }
- public func <<? <I, R, Error>(lhs: Function<I, R, Error>, rhs: I) -> Error? {
- switch lhs.invoke(rhs) {
- case .failure(let fail):
- return fail
- default:
- return nil
- }
- }
- let reciveDataFromLyricsService = Function
- <(Array<String>, (Data) throws -> String), String, Either<Either<NetworkFailure, URLError>, Either<CorruptedData, Any>>> {
- for adress in $0.0 {
- if let urladress = URL(string: adress) {
- let data = try? Data(contentsOf: urladress)
- if data == nil {
- throw Either<Either<NetworkFailure, URLError>, Either<CorruptedData, Any>>.b(.a(CorruptedData()))
- }
- do {
- return try $0.1(data!)
- } catch {
- throw Either<Either<NetworkFailure, URLError>, Either<CorruptedData, Any>>.b(.b(error))
- }
- } else {
- throw Either<Either<NetworkFailure, URLError>, Either<CorruptedData, Any>>.a(.b(URLError(URLError.Code(rawValue: 1))))
- }
- }
- }
- switch reciveDataFromLyricsService << (
- adresses: ["https://"],
- transforamationClosure: {
- String(data: $0, encoding: .utf8)!
- }
- ) {
- case .failure(let err): print("failed to load text due to \(err)")
- case .success(let str): print(str)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement