Created
June 1, 2017 18:02
-
-
Save RuiAAPeres/859f929873889f02b95af1b0bcf1c5da 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 | |
precedencegroup PipePrecedence { | |
associativity: left | |
higherThan: AssignmentPrecedence | |
} | |
infix operator |> : PipePrecedence | |
public func |> <T, U>(x: T, f: (T) -> U) -> U { | |
return f(x) | |
} | |
enum Result<T> { | |
case success(T) | |
case failure(String) | |
func map<U>(_ f: (T) -> U) -> Result<U> { | |
switch self { | |
case .success(let x): return .success(x |> f) | |
case .failure(let e): return .failure(e) | |
} | |
} | |
} | |
func calculator(_ input: String) -> Result<Double> { | |
return input |> split |> reversePolishNotation | |
} | |
func reversePolishNotation(_ input: [String]) -> Result<Double> { | |
let array = input.reduce(.success([]), _reversePolishNotation) | |
return array.map { $0.first! } | |
} | |
func _reversePolishNotation(_ input: Result<[Double]>, _ s: String) -> Result<[Double]> { | |
switch s { | |
case "+": | |
let sum: ([Double]) -> [Double] = { array in | |
return [array[0] + array[1]] + array[2..<array.count] | |
} | |
return input.map(sum) | |
default: | |
if let double = Double(s) { | |
return input.map { [double] + $0 } | |
} | |
return .failure("invalid input: \(s)") | |
} | |
} | |
func fake<T>(_ input: T) -> Double { return 0 } | |
func split(_ input: String) -> [String] { | |
return input.components(separatedBy: " ") | |
} | |
calculator("4 5 + 3 -") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment