Created
June 1, 2017 17:15
-
-
Save RuiAAPeres/c7eb204ac44941ee5cd6c0e29b8a7a41 to your computer and use it in GitHub Desktop.
This file contains 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 | |
"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