概要
paiza.ioでrustやってみた。
練習問題やってみた。
練習問題
Forthインタープリターを書いて、数9を4個つかって1から15までの数を表す式を実行せよ。
サンプルコード
const MAXVAL: usize = 20;
fn push(val: &mut [f32; MAXVAL], sp: &mut i32, op: f32) {
if *sp < MAXVAL as i32
{
val[*sp as usize] = op;
*sp += 1;
}
else
{
println!("error: stack full, can't push {}", op);
}
}
fn pop(val: &mut [f32; MAXVAL], sp: &mut i32) -> f32 {
if *sp > 0
{
*sp -= 1;
return val[*sp as usize];
}
else
{
println!("error: stack empty");
return 0.0;
}
}
fn Forth(s: &str) {
let mut sp: i32 = 0;
let mut val: [f32; MAXVAL] = [0.0; MAXVAL];
//println!("{}", s);
let strs = s.split_whitespace();
//println!("{:?}", strs);
let cs: Vec<&str> = s.split_whitespace().collect::<Vec<_>>();
//println!("{:?}", cs);
for token in cs
{
//println!("{}", token);
match token
{
"+" => {
let right = pop(&mut val, &mut sp);
let left = pop(&mut val, &mut sp);
push(&mut val, &mut sp, left + right);
}
"-" => {
let right = pop(&mut val, &mut sp);
let left = pop(&mut val, &mut sp);
push(&mut val, &mut sp, left - right);
}
"*" => {
let right = pop(&mut val, &mut sp);
let left = pop(&mut val, &mut sp);
push(&mut val, &mut sp, left * right);
}
"/" => {
let right = pop(&mut val, &mut sp);
let left = pop(&mut val, &mut sp);
push(&mut val, &mut sp, left / right);
}
"." => {
let right = pop(&mut val, &mut sp);
println!("{}", right);
}
"dup" => {
let right = pop(&mut val, &mut sp);
push(&mut val, &mut sp, right);
push(&mut val, &mut sp, right);
}
"drop" => {
let right = pop(&mut val, &mut sp);
}
_ => {
let number: f32 = token.parse::<f32>().expect("REASON");
push(&mut val, &mut sp, number);
}
}
}
}
fn main() {
Forth("9 9 - 9 9 / .");
Forth("9 9 / 9 9 / + .");
Forth("9 9 + 9 + 9 / .");
Forth("9 9 9 + 9 / dup + .");
Forth("9 9 9 + 9 / dup + - .");
Forth("9 dup 9 + 9 + 9 / - .");
Forth("9 9 9 + 9 / - .");
Forth("9 9 9 drop 9 / - .");
Forth("9 9 - 9 * 9 + .");
Forth("9 9 / 9 dup 9 / + .");
Forth("9 9 9 + 9 / + .");
Forth("9 dup 9 9 + + 9 / + .");
Forth("9 9 9 + 9 / dup + + .");
Forth("9 dup 9 9 + 9 / dup + - + .");
Forth("9 dup dup 9 + 9 + 9 / - + .");
}
実行結果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
成果物
以上