01mf02 / jaq

A jq clone focussed on correctness, speed, and simplicity

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Inconsistency with jq] Array subtraction not supported

Starwort opened this issue · comments

In jq:
jq -nc '[1,2,3]-[2,3,4]' # [1]

In jaq:
jaq -nc '[1,2,3]-[2,3,4]' # Error: cannot calculate [1,2,3] - [2,3,4]

Is this intentional? Is there a different method for calculating array differences?

My guess is it's not intentional. And the change is quite small and harmless, I think. You could send a PR to get it added in 😉

This is a diff with an O(n²) version, if you want to start from that.

diff --git a/jaq-interpret/src/val.rs b/jaq-interpret/src/val.rs
index 5e3178f..51932de 100644
--- a/jaq-interpret/src/val.rs
+++ b/jaq-interpret/src/val.rs
@@ -370,6 +370,10 @@ impl core::ops::Sub for Val {
             (Float(x), Float(y)) => Ok(Float(x - y)),
             (Num(n), r) => Self::from_dec_str(&n) - r,
             (l, Num(n)) => l - Self::from_dec_str(&n),
+            (Arr(mut l), Arr(r)) => {
+                Rc::make_mut(&mut l).retain(|le| !r.iter().any(|re| le == re));
+                Ok(Arr(l))
+            }
             (l, r) => Err(Error::MathOp(l, MathOp::Sub, r)),
         }
     }

Thanks @kklingenberg for providing me with such a nice template to implement this functionality!