Created
October 8, 2013 06:31
-
-
Save zh4ngx/6880395 to your computer and use it in GitHub Desktop.
Functional-ish version of stack machine
This file contains hidden or 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
$stack = [] | |
def solution(s) | |
s.each_char do |c| | |
case c | |
when /[0-9]/ | |
$stack.push c | |
puts c | |
when '+' | |
return -1 unless op_nums(lambda { |left, right| left + right }) | |
when '*' | |
return -1 unless op_nums(lambda { |left, right| left * right }) | |
end | |
end | |
return $stack.pop | |
end | |
def op_nums operation | |
left = $stack.pop | |
right = $stack.pop | |
if left and right | |
$stack.push operation.call(left.to_i, right.to_i) | |
else | |
false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment