概要
paiza.ioでrubyやってみた。
練習問題やってみた。
練習問題
forthインタープリタを書け。
数9を4個つかって1から15までの数を表す式を実行せよ。
classにせよ。
サンプルコード
class Forth
$stack = []
def add
top1 = $stack.pop()
top2 = $stack.pop()
v = top2 + top1
$stack.push(v)
end
def sub
top1 = $stack.pop()
top2 = $stack.pop()
v = top2 - top1
$stack.push(v)
end
def mul
top1 = $stack.pop()
top2 = $stack.pop()
v = top2 * top1
$stack.push(v)
end
def div
top1 = $stack.pop()
top2 = $stack.pop()
v = top2 / top1
$stack.push(v)
end
def dup
top1 = $stack.pop()
$stack.push(top1)
$stack.push(top1)
end
def drop
top1 = $stack.pop()
end
def get
top1 = $stack.pop()
puts top1
end
def push(v)
$stack.push(Integer(v))
end
def run(str)
s = str.split(' ')
for i in s do
#puts i
if i == "+"
add()
elsif i == "-"
sub()
elsif i == "*"
mul()
elsif i == "/"
div()
elsif i == "dup"
dup()
elsif i == "drop"
drop()
elsif i == "."
get()
else
push(i)
end
end
end
def initialize
run("9 9 - 9 9 / .")# 1
run("9 9 / 9 9 / + .")# 2
run("9 9 + 9 + 9 / .")# 3
run("9 9 9 + 9 / dup + .")# 4
run("9 9 9 + 9 / dup + - .")# 5
run("9 dup 9 + 9 + 9 / - .")# 6
run("9 9 9 + 9 / - .")# 7
run("9 9 9 drop 9 / - .")# 8
run("9 9 - 9 * 9 + .")# 9
run("9 9 / 9 dup 9 / + .")# 10
run("9 9 9 + 9 / + .")# 11
run("9 dup 9 9 + + 9 / + .")# 12
run("9 9 9 + 9 / dup + + .")# 13
run("9 dup 9 9 + 9 / dup + - + .")# 14
run("9 dup dup 9 + 9 + 9 / - + .")# 15
end
end
Forth.new
実行結果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
成果物
以上。