Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.