Skip to main content

nu_command/math/
product.rs

1use crate::math::{
2    reducers::{Reduce, reducer_for},
3    utils::{run_with_function_with_cell_paths, run_with_function_with_cell_paths_const},
4};
5use nu_engine::command_prelude::*;
6
7#[derive(Clone)]
8pub struct MathProduct;
9
10impl Command for MathProduct {
11    fn name(&self) -> &str {
12        "math product"
13    }
14
15    fn signature(&self) -> Signature {
16        Signature::build("math product")
17            .input_output_types(vec![
18                (Type::List(Box::new(Type::Number)), Type::Number),
19                (Type::Range, Type::Number),
20                (Type::table(), Type::record()),
21                (Type::record(), Type::record()),
22            ])
23            .allow_variants_without_examples(true)
24            .rest(
25                "columns",
26                SyntaxShape::CellPath,
27                "The cell-paths/columns to operate on.",
28            )
29            .category(Category::Math)
30    }
31
32    fn description(&self) -> &str {
33        "Returns the product of a list of numbers or the products of each column of a table."
34    }
35
36    fn search_terms(&self) -> Vec<&str> {
37        vec!["times", "multiply", "x", "*"]
38    }
39
40    fn is_const(&self) -> bool {
41        true
42    }
43
44    fn run(
45        &self,
46        engine_state: &EngineState,
47        stack: &mut Stack,
48        call: &Call,
49        input: PipelineData,
50    ) -> Result<PipelineData, ShellError> {
51        run_with_function_with_cell_paths(engine_state, stack, call, input, product)
52    }
53
54    fn run_const(
55        &self,
56        working_set: &StateWorkingSet,
57        call: &Call,
58        input: PipelineData,
59    ) -> Result<PipelineData, ShellError> {
60        run_with_function_with_cell_paths_const(working_set, call, input, product)
61    }
62
63    fn examples(&self) -> Vec<Example<'_>> {
64        vec![
65            Example {
66                description: "Compute the product of a list of numbers.",
67                example: "[2 3 3 4] | math product",
68                result: Some(Value::test_int(72)),
69            },
70            Example {
71                description: "Compute the product of each column in a table.",
72                example: "[[a b]; [1 2] [3 4]] | math product",
73                result: Some(Value::test_record(record! {
74                    "a" => Value::test_int(3),
75                    "b" => Value::test_int(8),
76                })),
77            },
78            Example {
79                description: "Compute the product of list-valued columns in a record.",
80                example: "{alice: [2 3 4], bob: [4 5 6]} | math product",
81                result: Some(Value::test_record(record! {
82                    "alice" => Value::test_int(24),
83                    "bob" => Value::test_int(120),
84                })),
85            },
86            Example {
87                description: "Compute the product of a single column using a cell path.",
88                example: "{alice: [2 3 4], bob: [4 5 6]} | math product alice",
89                result: Some(Value::test_record(record! {
90                    "alice" => Value::test_int(24),
91                    "bob" => Value::list(
92                        vec![Value::test_int(4), Value::test_int(5), Value::test_int(6)],
93                        Span::test_data(),
94                    ),
95                })),
96            },
97        ]
98    }
99}
100
101/// Calculate product of given values
102pub fn product(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
103    let product_func = reducer_for(Reduce::Product);
104    product_func(Value::nothing(head), values.to_vec(), span, head)
105}
106
107#[cfg(test)]
108mod test {
109    use super::*;
110
111    #[test]
112    fn test_examples() -> nu_test_support::Result {
113        nu_test_support::test().examples(MathProduct)
114    }
115}