From cfdb4bbf255ade8ee618d722f3291082c59e66bb Mon Sep 17 00:00:00 2001 From: Bahex Date: Mon, 16 Dec 2024 15:13:51 +0300 Subject: [PATCH] `std/iter scan`: change closure signature to be consistent with `reduce` (#14596) # Description I noticed that `std/iter scan`'s closure has the order of parameters reversed compared to `reduce`, so changed it to be consistent. Also it didn't have `$acc` as `$in` like `reduce`, so fixed that as well. # User-Facing Changes > [!WARNING] > This is a breaking change for all operations where order of `$it` and `$acc` matter. - This is still fine. ```nushell [1 2 3] | iter scan 0 {|x, y| $x + $y} ``` - This is broken ```nushell [a b c d] | iter scan "" {|x, y| [$x, $y] | str join} -n ``` and should be changed to either one of these - ```nushell [a b c d] | iter scan "" {|it, acc| [$acc, $it] | str join} -n ``` - ```nushell [a b c d] | iter scan "" {|it| append $it | str join} -n ``` # Tests + Formatting Only change is in the std and its tests - :green_circle: toolkit test stdlib # After Submitting Mention in release notes --- crates/nu-std/std/iter/mod.nu | 8 +++++--- crates/nu-std/tests/test_iter.nu | 5 ++++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/nu-std/std/iter/mod.nu b/crates/nu-std/std/iter/mod.nu index 8c25269690..daa62d2dba 100644 --- a/crates/nu-std/std/iter/mod.nu +++ b/crates/nu-std/std/iter/mod.nu @@ -101,8 +101,9 @@ export def intersperse [ # -> list # Returns a list of intermediate steps performed by `reduce` # (`fold`). It takes two arguments, an initial value to seed the # initial state and a closure that takes two arguments, the first -# being the internal state and the second the list element in the -# current iteration. +# being the list element in the current iteration and the second +# the internal state. +# The internal state is also provided as pipeline input. # # # Example # ``` @@ -123,7 +124,8 @@ export def scan [ # -> list --noinit(-n) # remove the initial value from the result ] { reduce --fold [$init] {|it, acc| - $acc ++ [(do $fn ($acc | last) $it)] + let acc_last = $acc | last + $acc ++ [($acc_last | do $fn $it $acc_last)] } | if $noinit { $in | skip diff --git a/crates/nu-std/tests/test_iter.nu b/crates/nu-std/tests/test_iter.nu index 2b768c3d9d..3ace342788 100644 --- a/crates/nu-std/tests/test_iter.nu +++ b/crates/nu-std/tests/test_iter.nu @@ -49,7 +49,10 @@ def iter_scan [] { let scanned = ([1 2 3] | iter scan 0 {|x, y| $x + $y}) assert equal $scanned [0, 1, 3, 6] - let scanned = ([a b c d] | iter scan "" {|x, y| [$x, $y] | str join} -n) + let scanned = ([a b c d] | iter scan "" {|it, acc| [$acc, $it] | str join} -n) + assert equal $scanned ["a" "ab" "abc" "abcd"] + + let scanned = ([a b c d] | iter scan "" {|it, acc| append $it | str join} -n) assert equal $scanned ["a" "ab" "abc" "abcd"] }