|
| 1 | +use crate::error_message; |
| 2 | +use crate::ifn::IFn; |
| 3 | +use crate::value::{ToValue, Value}; |
| 4 | +use std::rc::Rc; |
| 5 | + |
| 6 | +/// (gte x y) |
| 7 | +/// x >= y |
| 8 | +#[derive(Debug, Clone)] |
| 9 | +pub struct GteFn {} |
| 10 | +impl ToValue for GteFn { |
| 11 | + fn to_value(&self) -> Value { |
| 12 | + Value::IFn(Rc::new(self.clone())) |
| 13 | + } |
| 14 | +} |
| 15 | +impl IFn for GteFn { |
| 16 | + fn invoke(&self, args: Vec<Rc<Value>>) -> Value { |
| 17 | + if args.len() != 2 { |
| 18 | + return error_message::wrong_arg_count(2, args.len()); |
| 19 | + } |
| 20 | + match args.get(0).unwrap().to_value() { |
| 21 | + Value::I32(a) => match args.get(1).unwrap().to_value() { |
| 22 | + Value::I32(b) => Value::Boolean(a >= b), |
| 23 | + Value::F64(b) => Value::Boolean(a as f64 >= b), |
| 24 | + b_ => Value::Condition(format!( |
| 25 | + // TODO: what error message should be returned regarding using typetags? |
| 26 | + "Type mismatch; Expecting: (i32 | i64 | f32 | f64), Found: {}", |
| 27 | + b_.type_tag() |
| 28 | + )), |
| 29 | + }, |
| 30 | + Value::F64(a) => match args.get(0).unwrap().to_value() { |
| 31 | + Value::I32(b) => Value::Boolean(a >= b as f64), |
| 32 | + Value::F64(b) => Value::Boolean(a >= b), |
| 33 | + b_ => Value::Condition(format!( |
| 34 | + // TODO: what error message should be returned regarding using typetags? |
| 35 | + "Type mismatch; Expecting: (i32 | i64 | f32 | f64), Found: {}", |
| 36 | + b_.type_tag() |
| 37 | + )), |
| 38 | + }, |
| 39 | + a_ => Value::Condition(format!( |
| 40 | + // TODO: what error message should be returned regarding using typetags? |
| 41 | + "Type mismatch; Expecting: (i32 | i64 | f32 | f64), Found: {}", |
| 42 | + a_.type_tag() |
| 43 | + )), |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +#[cfg(test)] |
| 49 | +mod tests { |
| 50 | + mod gte_tests { |
| 51 | + use crate::ifn::IFn; |
| 52 | + use crate::rust_core::GteFn; |
| 53 | + use crate::value::Value; |
| 54 | + use std::rc::Rc; |
| 55 | + |
| 56 | + #[test] |
| 57 | + fn one_is_greater_than_zero() { |
| 58 | + let gte = GteFn {}; |
| 59 | + let args = vec![Rc::new(Value::I32(1)), Rc::new(Value::I32(0))]; |
| 60 | + assert_eq!(Value::Boolean(true), gte.invoke(args)); |
| 61 | + } |
| 62 | + |
| 63 | + #[test] |
| 64 | + fn one_is_gte_than_one() { |
| 65 | + let gte = GteFn {}; |
| 66 | + let args = vec![Rc::new(Value::I32(1)), Rc::new(Value::I32(1))]; |
| 67 | + assert_eq!(Value::Boolean(true), gte.invoke(args)); |
| 68 | + } |
| 69 | + |
| 70 | + #[test] |
| 71 | + fn one_is_not_gte_than_one_and_fractions() { |
| 72 | + let gte = GteFn {}; |
| 73 | + let args = vec![Rc::new(Value::I32(1)), Rc::new(Value::F64(1.00001))]; |
| 74 | + assert_eq!(Value::Boolean(false), gte.invoke(args)); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments