mirror of
https://github.com/teo3300/rust-mal.git
synced 2026-01-12 09:15:32 +01:00
Fixed integer operations evaluation recursively
Signed-off-by: teo3300 <matteo.rogora@live.it>
This commit is contained in:
36
src/types.rs
36
src/types.rs
@ -71,17 +71,29 @@ pub fn unescape_str(s: &str) -> String {
|
||||
|
||||
use MalType::Int;
|
||||
|
||||
pub fn int_op(set: isize, f: fn(isize, isize) -> isize, args: MalArgs) -> MalRet {
|
||||
let mut tmp: isize = set;
|
||||
for el in args {
|
||||
match el {
|
||||
Int(val) => {
|
||||
tmp = f(tmp, val);
|
||||
}
|
||||
_ => {
|
||||
return Err(format!("{:?} is not a number", el));
|
||||
}
|
||||
}
|
||||
fn if_number(val: MalType) -> Result<isize, String> {
|
||||
match val {
|
||||
Int(val) => Ok(val),
|
||||
_ => Err(format!("{:?} is not a number", val)),
|
||||
}
|
||||
}
|
||||
|
||||
fn int_op_rec(f: fn(isize, isize) -> isize, args: &MalArgs) -> Result<isize, String> {
|
||||
if args.len() == 1 {
|
||||
return if_number(args[0].clone());
|
||||
}
|
||||
|
||||
// PLEASE fix this
|
||||
let left = int_op_rec(f, &args[..args.len() - 1].to_vec())?;
|
||||
let right = if_number(args[args.len() - 1].clone())?;
|
||||
|
||||
Ok(f(left, right))
|
||||
}
|
||||
|
||||
pub fn int_op(set: isize, f: fn(isize, isize) -> isize, args: MalArgs) -> MalRet {
|
||||
if args.is_empty() {
|
||||
Ok(Int(set))
|
||||
} else {
|
||||
Ok(Int(int_op_rec(f, &args)?))
|
||||
}
|
||||
Ok(Int(tmp))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user