nu_command/filters/
reduce.rs

1use nu_engine::{command_prelude::*, ClosureEval};
2use nu_protocol::engine::Closure;
3
4#[derive(Clone)]
5pub struct Reduce;
6
7impl Command for Reduce {
8    fn name(&self) -> &str {
9        "reduce"
10    }
11
12    fn signature(&self) -> Signature {
13        Signature::build("reduce")
14            .input_output_types(vec![
15                (Type::List(Box::new(Type::Any)), Type::Any),
16                (Type::table(), Type::Any),
17                (Type::Range, Type::Any),
18            ])
19            .named(
20                "fold",
21                SyntaxShape::Any,
22                "reduce with initial value",
23                Some('f'),
24            )
25            .required(
26                "closure",
27                SyntaxShape::Closure(Some(vec![SyntaxShape::Any, SyntaxShape::Any])),
28                "Reducing function.",
29            )
30            .allow_variants_without_examples(true)
31            .category(Category::Filters)
32    }
33
34    fn description(&self) -> &str {
35        "Aggregate a list (starting from the left) to a single value using an accumulator closure."
36    }
37
38    fn search_terms(&self) -> Vec<&str> {
39        vec!["map", "fold", "foldl"]
40    }
41
42    fn examples(&self) -> Vec<Example> {
43        vec![
44            Example {
45                example: "[ 1 2 3 4 ] | reduce {|it, acc| $it + $acc }",
46                description: "Sum values of a list (same as 'math sum')",
47                result: Some(Value::test_int(10)),
48            },
49            Example {
50                example: "[ 1 2 3 4 ] | reduce {|it, acc| $acc - $it }",
51                description: r#"`reduce` accumulates value from left to right, equivalent to (((1 - 2) - 3) - 4)."#,
52                result: Some(Value::test_int(-8)),
53            },
54            Example {
55                example:
56                    "[ 8 7 6 ] | enumerate | reduce --fold 0 {|it, acc| $acc + $it.item + $it.index }",
57                description: "Sum values of a list, plus their indexes",
58                result: Some(Value::test_int(24)),
59            },
60            Example {
61                example: "[ 1 2 3 4 ] | reduce --fold 10 {|it, acc| $acc + $it }",
62                description: "Sum values with a starting value (fold)",
63                result: Some(Value::test_int(20)),
64            },
65            Example {
66                example: r#"[[foo baz] [baz quux]] | reduce --fold "foobar" {|it, acc| $acc | str replace $it.0 $it.1}"#,
67                description: "Iteratively perform string replace (from left to right): 'foobar' -> 'bazbar' -> 'quuxbar'",
68                result: Some(Value::test_string("quuxbar")),
69            },
70            Example {
71                example: r#"[ i o t ] | reduce --fold "Arthur, King of the Britons" {|it, acc| $acc | str replace --all $it "X" }"#,
72                description: "Replace selected characters in a string with 'X'",
73                result: Some(Value::test_string("ArXhur, KXng Xf Xhe BrXXXns")),
74            },
75            Example {
76                example: r#"['foo.gz', 'bar.gz', 'baz.gz'] | enumerate | reduce --fold '' {|str all| $"($all)(if $str.index != 0 {'; '})($str.index + 1)-($str.item)" }"#,
77                description:
78                    "Add ascending numbers to each of the filenames, and join with semicolons.",
79                result: Some(Value::test_string("1-foo.gz; 2-bar.gz; 3-baz.gz")),
80            },
81            Example {
82                example: r#"let s = "Str"; 0..2 | reduce --fold '' {|it, acc| $acc + $s}"#,
83                description:
84                    "Concatenate a string with itself, using a range to determine the number of times.",
85                result: Some(Value::test_string("StrStrStr")),
86            },
87            Example {
88                example: r#"[{a: 1} {b: 2} {c: 3}] | reduce {|it| merge $it}"#,
89                description: "Merge multiple records together, making use of the fact that the accumulated value is also supplied as pipeline input to the closure.",
90                result: Some(Value::test_record(record!(
91                    "a" => Value::test_int(1),
92                    "b" => Value::test_int(2),
93                    "c" => Value::test_int(3),
94                ))),
95            }
96        ]
97    }
98
99    fn run(
100        &self,
101        engine_state: &EngineState,
102        stack: &mut Stack,
103        call: &Call,
104        input: PipelineData,
105    ) -> Result<PipelineData, ShellError> {
106        let head = call.head;
107        let fold: Option<Value> = call.get_flag(engine_state, stack, "fold")?;
108        let closure: Closure = call.req(engine_state, stack, 0)?;
109
110        let mut iter = input.into_iter();
111
112        let mut acc = fold
113            .or_else(|| iter.next())
114            .ok_or_else(|| ShellError::GenericError {
115                error: "Expected input".into(),
116                msg: "needs input".into(),
117                span: Some(head),
118                help: None,
119                inner: vec![],
120            })?;
121
122        let mut closure = ClosureEval::new(engine_state, stack, closure);
123
124        for value in iter {
125            engine_state.signals().check(head)?;
126            acc = closure
127                .add_arg(value)
128                .add_arg(acc.clone())
129                .run_with_input(PipelineData::Value(acc, None))?
130                .into_value(head)?;
131        }
132
133        Ok(acc.with_span(head).into_pipeline_data())
134    }
135}
136
137#[cfg(test)]
138mod test {
139    use super::*;
140
141    #[test]
142    fn test_examples() {
143        use crate::{test_examples_with_commands, Merge};
144
145        test_examples_with_commands(Reduce {}, &[&Merge])
146    }
147}