From dbd60ed4f46fd4abbb675aac83195f8668978b72 Mon Sep 17 00:00:00 2001 From: suimong Date: Sat, 20 Jul 2024 01:55:38 +0800 Subject: [PATCH] Tiny make up to the documentation of `reduce` (#13408) This tiny PR improves the documentation of the `reduce` command by explicitly stating the direction of reduction, i.e. from left to right, and adds an example for demonstration. --------- Co-authored-by: Ben Yang --- crates/nu-command/src/filters/reduce.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/nu-command/src/filters/reduce.rs b/crates/nu-command/src/filters/reduce.rs index 87fbe3b23e..824e7709e5 100644 --- a/crates/nu-command/src/filters/reduce.rs +++ b/crates/nu-command/src/filters/reduce.rs @@ -36,7 +36,7 @@ impl Command for Reduce { } fn usage(&self) -> &str { - "Aggregate a list to a single value using an accumulator closure." + "Aggregate a list (starting from the left) to a single value using an accumulator closure." } fn search_terms(&self) -> Vec<&str> { @@ -50,6 +50,11 @@ impl Command for Reduce { description: "Sum values of a list (same as 'math sum')", result: Some(Value::test_int(10)), }, + Example { + example: "[ 1 2 3 4 ] | reduce {|it, acc| $acc - $it }", + description: r#"`reduce` accumulates value from left to right, equivalent to (((1 - 2) - 3) - 4)."#, + result: Some(Value::test_int(-8)), + }, Example { example: "[ 8 7 6 ] | enumerate | reduce --fold 0 {|it, acc| $acc + $it.item + $it.index }", @@ -61,6 +66,11 @@ impl Command for Reduce { description: "Sum values with a starting value (fold)", result: Some(Value::test_int(20)), }, + Example { + example: r#"[[foo baz] [baz quux]] | reduce --fold "foobar" {|it, acc| $acc | str replace $it.0 $it.1}"#, + description: "Iteratively perform string replace (from left to right): 'foobar' -> 'bazbar' -> 'quuxbar'", + result: Some(Value::test_string("quuxbar")), + }, Example { example: r#"[ i o t ] | reduce --fold "Arthur, King of the Britons" {|it, acc| $acc | str replace --all $it "X" }"#, description: "Replace selected characters in a string with 'X'",