nu_command/math/
sum.rs

1use crate::math::{
2    reducers::{Reduce, reducer_for},
3    utils::run_with_function,
4};
5use nu_engine::command_prelude::*;
6
7#[derive(Clone)]
8pub struct MathSum;
9
10impl Command for MathSum {
11    fn name(&self) -> &str {
12        "math sum"
13    }
14
15    fn signature(&self) -> Signature {
16        Signature::build("math sum")
17            .input_output_types(vec![
18                (Type::List(Box::new(Type::Number)), Type::Number),
19                (Type::List(Box::new(Type::Duration)), Type::Duration),
20                (Type::List(Box::new(Type::Filesize)), Type::Filesize),
21                (Type::Range, Type::Number),
22                (Type::table(), Type::record()),
23                (Type::record(), Type::record()),
24            ])
25            .allow_variants_without_examples(true)
26            .category(Category::Math)
27    }
28
29    fn description(&self) -> &str {
30        "Returns the sum of a list of numbers or of each column in a table."
31    }
32
33    fn search_terms(&self) -> Vec<&str> {
34        vec!["plus", "add", "total", "+"]
35    }
36
37    fn is_const(&self) -> bool {
38        true
39    }
40
41    fn run(
42        &self,
43        _engine_state: &EngineState,
44        _stack: &mut Stack,
45        call: &Call,
46        input: PipelineData,
47    ) -> Result<PipelineData, ShellError> {
48        run_with_function(call, input, summation)
49    }
50
51    fn run_const(
52        &self,
53        _working_set: &StateWorkingSet,
54        call: &Call,
55        input: PipelineData,
56    ) -> Result<PipelineData, ShellError> {
57        run_with_function(call, input, summation)
58    }
59
60    fn examples(&self) -> Vec<Example> {
61        vec![
62            Example {
63                description: "Sum a list of numbers",
64                example: "[1 2 3] | math sum",
65                result: Some(Value::test_int(6)),
66            },
67            Example {
68                description: "Get the disk usage for the current directory",
69                example: "ls | get size | math sum",
70                result: None,
71            },
72            Example {
73                description: "Compute the sum of each column in a table",
74                example: "[[a b]; [1 2] [3 4]] | math sum",
75                result: Some(Value::test_record(record! {
76                    "a" => Value::test_int(4),
77                    "b" => Value::test_int(6),
78                })),
79            },
80        ]
81    }
82}
83
84pub fn summation(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
85    let sum_func = reducer_for(Reduce::Summation);
86    sum_func(Value::nothing(head), values.to_vec(), span, head)
87}
88
89#[cfg(test)]
90mod test {
91    use super::*;
92
93    #[test]
94    fn test_examples() {
95        use crate::test_examples;
96
97        test_examples(MathSum {})
98    }
99}