Skip to content

Commit d889d90

Browse files
committed
define sub in terms of neg and add; add test cases
1 parent fc431a3 commit d889d90

File tree

2 files changed

+31
-7
lines changed

2 files changed

+31
-7
lines changed

src/v1/value/value_utils.rs

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use num_bigint::BigInt;
33
use num_traits::Zero;
44
use std::{
55
collections::BTreeMap,
6-
ops::{Add, Mul, Not, Sub},
6+
ops::{Add, Mul, Neg, Not, Sub},
77
};
88

99
use super::{CurrencySymbol, TokenName, Value};
@@ -133,6 +133,22 @@ impl Add<&Value> for &Value {
133133
}
134134
}
135135

136+
impl Neg for Value {
137+
type Output = Value;
138+
139+
fn neg(self) -> Self::Output {
140+
(&self).neg()
141+
}
142+
}
143+
144+
impl Neg for &Value {
145+
type Output = Value;
146+
147+
fn neg(self) -> Self::Output {
148+
self.map_amount(|_, _, a| a.neg())
149+
}
150+
}
151+
136152
forward_val_val_binop!(impl Sub for Value, sub);
137153
forward_ref_val_binop!(impl Sub for Value, sub);
138154
forward_val_ref_binop!(impl Sub for Value, sub);
@@ -141,11 +157,7 @@ impl Sub<&Value> for &Value {
141157
type Output = Value;
142158

143159
fn sub(self, rhs: &Value) -> Self::Output {
144-
Value(union_b_tree_maps_with(
145-
|lhs, rhs| union_b_tree_maps_with(|lhs, rhs| lhs - rhs, lhs, rhs),
146-
&self.0,
147-
&rhs.0,
148-
))
160+
self.add(rhs.neg())
149161
}
150162
}
151163

tests/value.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
#[cfg(test)]
22
mod value_tests {
3-
mod semiring {
3+
mod ring_ish {
4+
use std::ops::Neg;
5+
46
use num_bigint::BigInt;
57
use num_traits::{One, Zero};
68
use plutus_ledger_api::{
@@ -60,6 +62,16 @@ mod value_tests {
6062
assert_eq!(&val * BigInt::zero(), BigInt::zero() * &val);
6163
assert_eq!(Value::zero(), (BigInt::zero() * &val).normalize());
6264
}
65+
66+
#[test]
67+
fn test_additive_inverse_annihilation(val in arb_value()) {
68+
assert_eq!((&val + (&val).neg()).normalize(), Value::zero());
69+
}
70+
71+
#[test]
72+
fn test_minus(x in arb_value(), y in arb_value()) {
73+
assert_eq!(&x - &y, &x + (&y).neg());
74+
}
6375
}
6476
}
6577

0 commit comments

Comments
 (0)