Skip to content

Instantly share code, notes, and snippets.

@RuiAAPeres
Created June 1, 2017 17:37
Show Gist options
  • Save RuiAAPeres/f079b925fc43f644ea9a0077bd808082 to your computer and use it in GitHub Desktop.
Save RuiAAPeres/f079b925fc43f644ea9a0077bd808082 to your computer and use it in GitHub Desktop.
import Foundation
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) -> Double {
return input |> split |> reversePolishNotation
}
func reversePolishNotation(_ input: [String]) -> Double {
let array = input.reduce([], _reversePolishNotation)
return array.first!
}
func _reversePolishNotation(_ input: [Double], _ s: String) -> [Double] {
switch s {
case "+":
return [input[0] + input[1]] + input[2..<input.count]
default:
if let double = Double(s) {
return [double] + input
}
return input
}
}
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