malachite_q/rational_vector/arithmetic/element_sum.rs
1// Copyright © 2026 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::Rational;
10use crate::rational_vector::RationalVector;
11use malachite_base::num::arithmetic::traits::ElementSum;
12
13impl ElementSum for RationalVector {
14 type Output = Rational;
15
16 /// Returns the sum of the elements of a [`RationalVector`], taking the vector by reference.
17 ///
18 /// The 0-dimensional vector has no elements, and their sum is 0.
19 ///
20 /// $$
21 /// f(v) = \sum_i v_i.
22 /// $$
23 ///
24 /// # Worst-case complexity
25 /// $T(n) = O(n)$
26 ///
27 /// $M(n) = O(n)$
28 ///
29 /// where $T$ is time, $M$ is additional memory, and $n$ is the total number of bits of the
30 /// elements.
31 ///
32 /// # Examples
33 /// ```
34 /// use core::str::FromStr;
35 /// use malachite_base::num::arithmetic::traits::ElementSum;
36 /// use malachite_q::rational_vector::RationalVector;
37 ///
38 /// assert_eq!(
39 /// RationalVector::from_str("(1/2, -1/3)")
40 /// .unwrap()
41 /// .to_element_sum()
42 /// .to_string(),
43 /// "1/6"
44 /// );
45 /// assert_eq!(RationalVector::from_str("()").unwrap().to_element_sum(), 0);
46 /// ```
47 #[inline]
48 fn to_element_sum(&self) -> Rational {
49 self.elements.iter().sum()
50 }
51
52 /// Returns the sum of the elements of a [`RationalVector`], taking the vector by value.
53 ///
54 /// The 0-dimensional vector has no elements, and their sum is 0.
55 ///
56 /// $$
57 /// f(v) = \sum_i v_i.
58 /// $$
59 ///
60 /// # Worst-case complexity
61 /// $T(n) = O(n)$
62 ///
63 /// $M(n) = O(n)$
64 ///
65 /// where $T$ is time, $M$ is additional memory, and $n$ is the total number of bits of the
66 /// elements.
67 ///
68 /// # Examples
69 /// ```
70 /// use core::str::FromStr;
71 /// use malachite_base::num::arithmetic::traits::ElementSum;
72 /// use malachite_q::rational_vector::RationalVector;
73 ///
74 /// assert_eq!(
75 /// RationalVector::from_str("(1/2, -1/3)")
76 /// .unwrap()
77 /// .into_element_sum()
78 /// .to_string(),
79 /// "1/6"
80 /// );
81 /// assert_eq!(
82 /// RationalVector::from_str("()").unwrap().into_element_sum(),
83 /// 0
84 /// );
85 /// ```
86 #[inline]
87 fn into_element_sum(self) -> Rational {
88 self.elements.into_iter().sum()
89 }
90}