2022-02-14 03:22:51 +01:00
|
|
|
---
|
|
|
|
title: reduce
|
|
|
|
layout: command
|
|
|
|
version: 0.59.0
|
|
|
|
---
|
|
|
|
|
2021-05-30 02:57:04 +02:00
|
|
|
Aggregate a list table to a single value using an accumulator block.
|
|
|
|
|
2022-02-14 03:22:51 +01:00
|
|
|
## Signature
|
2021-05-30 02:57:04 +02:00
|
|
|
|
2022-02-14 03:22:51 +01:00
|
|
|
```> reduce (block) --fold --numbered```
|
2021-05-30 02:57:04 +02:00
|
|
|
|
|
|
|
## Parameters
|
|
|
|
|
2022-02-14 03:22:51 +01:00
|
|
|
- `block`: reducing function
|
|
|
|
- `--fold {any}`: reduce with initial value
|
|
|
|
- `--numbered`: iterate with an index
|
2021-05-30 02:57:04 +02:00
|
|
|
|
|
|
|
## Examples
|
2022-02-14 03:22:51 +01:00
|
|
|
|
|
|
|
Sum values of a list (same as 'math sum')
|
2021-05-30 02:57:04 +02:00
|
|
|
```shell
|
2022-02-20 02:13:33 +01:00
|
|
|
> [ 1 2 3 4 ] | reduce {|it, acc| $it + $acc }
|
2022-02-14 03:22:51 +01:00
|
|
|
```
|
2021-05-30 02:57:04 +02:00
|
|
|
|
2022-02-14 03:22:51 +01:00
|
|
|
Sum values with a starting value (fold)
|
2021-05-30 02:57:04 +02:00
|
|
|
```shell
|
2022-02-20 02:13:33 +01:00
|
|
|
> [ 1 2 3 4 ] | reduce -f 10 {|it, acc| $acc + $it }
|
2022-02-14 03:22:51 +01:00
|
|
|
```
|
2021-05-30 02:57:04 +02:00
|
|
|
|
2022-02-14 03:22:51 +01:00
|
|
|
Replace selected characters in a string with 'X'
|
2021-05-30 02:57:04 +02:00
|
|
|
```shell
|
2022-02-20 02:13:33 +01:00
|
|
|
> [ i o t ] | reduce -f "Arthur, King of the Britons" {|it, acc| $acc | str find-replace -a $it "X" }
|
2022-02-14 03:22:51 +01:00
|
|
|
```
|
2021-05-30 02:57:04 +02:00
|
|
|
|
2022-02-14 03:22:51 +01:00
|
|
|
Find the longest string and its index
|
2021-05-30 02:57:04 +02:00
|
|
|
```shell
|
2022-02-20 02:13:33 +01:00
|
|
|
> [ one longest three bar ] | reduce -n { |it, acc|
|
|
|
|
if ($it.item | str length) > ($acc | str length) {
|
2022-02-14 03:22:51 +01:00
|
|
|
$it.item
|
|
|
|
} else {
|
2022-02-20 02:13:33 +01:00
|
|
|
$acc
|
2022-02-14 03:22:51 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
2021-05-30 02:57:04 +02:00
|
|
|
|