Skip to content

Instantly share code, notes, and snippets.

@tasuten
Created July 1, 2012 12:42
Show Gist options
  • Save tasuten/3028328 to your computer and use it in GitHub Desktop.
Save tasuten/3028328 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calc by Ruby
#!/usr/bin/env ruby
# encoding : utf-8
# Complexクラスは1.9.xでは組み込みクラスになった
# require 'complex'
include Math
ONE_ARG_FUNCS = %w(sin cos tan asin acos atan sinh cosh tanh asinh acosh atanh exp log log10 log2 sqrt)
stack = []
continue = true
fold_mode = false
while continue == true
gets.chomp.split.each do |input|
# 引数一個の数学関数
if ONE_ARG_FUNCS.member?(input)
stack.push(send(input, stack.pop))
# eval("stack.push(#{input}(stack.pop))")
next
end
# fold
if fold_mode == true
case input
when '+', '-', '*', '/', '**', '^'
# 初期値の設定
case input
when '+', '-'
init = 0
when '*', '/'
init = 1
when '**', '^'
init = stack.pop
input = '**'
end
until stack.empty?
eval("init #{input}= stack.pop")
end
stack.push(init)
end
fold_mode = false
next
end
case input
when /^[\+|\-]?\d+$/
stack.push(input.to_i)
when /^[\+|\-]?\d+\.\d*$/
stack.push(input.to_f)
when /^[\+\-]?\d*\.?\d*[\+\-]?\d*\.?\d*i$/
stack.push(input.to_c)
when 'PI'
stack.push(PI)
when 'E'
stack.push(E)
when 'I'
stack.push(Complex::I)
when '+'
stack.push(stack.pop + stack.pop)
when '-'
stack.push(stack.pop - stack.pop)
when '*'
stack.push(stack.pop * stack.pop)
when '/'
stack.push(stack.pop / stack.pop)
when '%'
stack.push(stack.pop % stack.pop)
when '**', '^'
stack.push(stack.pop ** stack.pop)
when 'abs'
stack.push((stack.pop).abs)
when 'inverse'
stack.reverse!
when 'fold', 'inject'
fold_mode = true
# スタックの一番頭の要素をpop(削除)
when 'pop'
stack.pop
when 'exit', 'q', 'quit', 'bye'
continue = false
end
end
p stack
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment