Skip to content

Instantly share code, notes, and snippets.

@RuiAAPeres
Created June 1, 2017 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RuiAAPeres/c7eb204ac44941ee5cd6c0e29b8a7a41 to your computer and use it in GitHub Desktop.
Save RuiAAPeres/c7eb204ac44941ee5cd6c0e29b8a7a41 to your computer and use it in GitHub Desktop.
import Foundation
"4 5 + 3 +"
func calculator(_ input: String) -> Double {
return input |> split |> reversePolishNotation
}
func reversePolishNotation(_ input: [String]) -> Double {
var stack: [Double] = []
for s in input {
if let double = Double(s) {
stack = [double] + stack
}
else {
stack = applyOperator(stack, s)
}
}
return stack.first!
}
func applyOperator(_ input: [Double], _ op: String) -> [Double] {
switch op {
case "+":
return [input[0] + input[1]] + input[1..<input.count]
default:
return input
}
}
func fake<T>(_ input: T) -> Double { return 0 }
func split(_ input: String) -> [String] {
return input.components(separatedBy: " ")
}
calculator("4 5 +")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment