Skip to content

Instantly share code, notes, and snippets.

@tiffany352
Created August 8, 2013 21:56
Show Gist options
  • Save tiffany352/6189149 to your computer and use it in GitHub Desktop.
Save tiffany352/6189149 to your computer and use it in GitHub Desktop.
My first non-hello rust program
use std::os;
enum Token {
Add,
Sub,
Mul,
Div,
Mod,
Func {name: ~str, args: ~[~str]},
Num (int),
Nil
}
fn parse_token(text: &str) -> Token {
match FromStr::from_str::<int>(text) {
Some(x) => Num(x),
None => match text {
"+" => Add,
"-" => Sub,
"*" => Mul,
"/" => Div,
"%" => Mod,
_ => Nil
}
}
}
fn handle_token(tok: Token, stack: &[int]) -> Option<~[int]> {
match tok {
Num(x) => Some(~[x] + stack),
Add => match stack {
[a, b, ..rest] => Some(~[a+b] + rest),
_ => None
},
Sub => match stack {
[a, b, ..rest] => Some(~[a-b] + rest),
_ => None
},
Mul => match stack {
[a, b, ..rest] => Some(~[a*b] + rest),
_ => None
},
Div => match stack {
[a, b, ..rest] => Some(~[a/b] + rest),
_ => None
},
Mod => match stack {
[a, b, ..rest] => Some(~[a%b] + rest),
_ => None
},
_ => None
}
}
fn main() {
let mut stack : ~[int] = ~[];
let args = os::args();
for args.iter().advance |arg| {
let tok = parse_token(*arg);
//println(fmt!("%?", tok));
let res : Option<~[int]> = handle_token(tok, stack);
match res {
Some(r) => stack = r,
None => ()
}
}
match stack {
[a] => println(fmt!("Result: %i", a)),
_ => println("No result?")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment