Skip to content

Instantly share code, notes, and snippets.

@RuiAAPeres
Created June 1, 2017 18:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RuiAAPeres/859f929873889f02b95af1b0bcf1c5da to your computer and use it in GitHub Desktop.
Save RuiAAPeres/859f929873889f02b95af1b0bcf1c5da to your computer and use it in GitHub Desktop.
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