|
| 1 | +use crate::ifn::IFn; |
| 2 | +use crate::value::{ToValue, Value}; |
| 3 | +use std::rc::Rc; |
| 4 | + |
| 5 | +/// (assoc map key val & kvs) |
| 6 | +/// |
| 7 | +// General assoc fn; however, currently just implemented |
| 8 | +// for our one map type, PersistentListMap |
| 9 | +#[derive(Debug, Clone)] |
| 10 | +pub struct EqualsFn {} |
| 11 | +impl ToValue for EqualsFn { |
| 12 | + fn to_value(&self) -> Value { |
| 13 | + Value::IFn(Rc::new(self.clone())) |
| 14 | + } |
| 15 | +} |
| 16 | +impl IFn for EqualsFn { |
| 17 | + fn invoke(&self, args: Vec<Rc<Value>>) -> Value { |
| 18 | + if args.is_empty() { |
| 19 | + //@TODO use proper error function |
| 20 | + return Value::Condition(format!( |
| 21 | + "Wrong number of arguments given to function (Given: {}, Expected: > 0)", |
| 22 | + args.len() |
| 23 | + )); |
| 24 | + } |
| 25 | + |
| 26 | + for pair in args.windows(2) { |
| 27 | + let a = &pair[0]; |
| 28 | + let b = &pair[1]; |
| 29 | + if a != b { |
| 30 | + return Value::Boolean(false); |
| 31 | + } |
| 32 | + }; |
| 33 | + Value::Boolean(true) |
| 34 | + |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +mod tests { |
| 39 | + use crate::value::{Value,ToValue}; |
| 40 | + use crate::rust_core::EqualsFn; |
| 41 | + use crate::keyword::Keyword; |
| 42 | + use crate::ifn::IFn; |
| 43 | + |
| 44 | + // Just checks that different Values do not count as equal, and that |
| 45 | + // at least one Value of the same kind does, and that one Value of the same |
| 46 | + // kind and different Value doesn't |
| 47 | + // |
| 48 | + // Otherwise, does not test every type |
| 49 | + #[test] |
| 50 | + fn equals_basic() { |
| 51 | + let equals = EqualsFn{}; |
| 52 | + let _i32 = Value::I32(1).to_rc_value(); |
| 53 | + // To test that we're not getting some sort of 'memory equality' |
| 54 | + let i32_copy = Value::I32(1).to_rc_value(); |
| 55 | + assert!(equals.invoke(vec![i32_copy.clone(),_i32.clone()]).is_truthy()); |
| 56 | + assert!(equals.invoke(vec![_i32.clone(),_i32.clone()]).is_truthy()); |
| 57 | + |
| 58 | + let i32_2 = Value::I32(5).to_rc_value(); |
| 59 | + assert!(!equals.invoke(vec![_i32.clone(),i32_2.clone()]).is_truthy()); |
| 60 | + |
| 61 | + let keyword = Keyword::intern("cat").to_rc_value(); |
| 62 | + let keyword2 = Keyword::intern("cat").to_rc_value(); |
| 63 | + let keyword3 = Keyword::intern("dog").to_rc_value(); |
| 64 | + |
| 65 | + assert!(equals.invoke(vec![keyword.clone(),keyword2.clone()]).is_truthy()); |
| 66 | + assert!(!equals.invoke(vec![keyword2,keyword3]).is_truthy()); |
| 67 | + assert!(!equals.invoke(vec![keyword,_i32]).is_truthy()); |
| 68 | + } |
| 69 | +} |
0 commit comments