1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use std::sync::atomic::Ordering;
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::{
Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, SyntaxShape, Value,
};
#[derive(Clone)]
pub struct Reduce;
impl Command for Reduce {
fn name(&self) -> &str {
"reduce"
}
fn signature(&self) -> Signature {
Signature::build("reduce")
.named(
"fold",
SyntaxShape::Any,
"reduce with initial value",
Some('f'),
)
.required(
"block",
SyntaxShape::Block(Some(vec![SyntaxShape::Any, SyntaxShape::Any])),
"reducing function",
)
.switch("numbered", "iterate with an index", Some('n'))
}
fn usage(&self) -> &str {
"Aggregate a list table to a single value using an accumulator block."
}
fn search_terms(&self) -> Vec<&str> {
vec!["map", "fold", "foldl"]
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
example: "[ 1 2 3 4 ] | reduce {|it, acc| $it + $acc }",
description: "Sum values of a list (same as 'math sum')",
result: Some(Value::Int {
val: 10,
span: Span::test_data(),
}),
},
Example {
example: "[ 1 2 3 ] | reduce -n {|it, acc| $acc.item + $it.item }",
description: "Sum values of a list (same as 'math sum')",
result: Some(Value::Int {
val: 6,
span: Span::test_data(),
}),
},
Example {
example: "[ 1 2 3 4 ] | reduce -f 10 {|it, acc| $acc + $it }",
description: "Sum values with a starting value (fold)",
result: Some(Value::Int {
val: 20,
span: Span::test_data(),
}),
},
Example {
example: r#"[ i o t ] | reduce -f "Arthur, King of the Britons" {|it, acc| $acc | str replace -a $it "X" }"#,
description: "Replace selected characters in a string with 'X'",
result: Some(Value::String {
val: "ArXhur, KXng Xf Xhe BrXXXns".to_string(),
span: Span::test_data(),
}),
},
Example {
example: r#"[ one longest three bar ] | reduce -n { |it, acc|
if ($it.item | str length) > ($acc.item | str length) {
$it.item
} else {
$acc.item
}
}"#,
description: "Find the longest string and its index",
result: Some(Value::String {
val: "longest".to_string(),
span: Span::test_data(),
}),
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let span = call.head;
let fold: Option<Value> = call.get_flag(engine_state, stack, "fold")?;
let numbered = call.has_flag("numbered");
let capture_block: CaptureBlock = call.req(engine_state, stack, 0)?;
let mut stack = stack.captures_to_stack(&capture_block.captures);
let block = engine_state.get_block(capture_block.block_id);
let ctrlc = engine_state.ctrlc.clone();
let orig_env_vars = stack.env_vars.clone();
let orig_env_hidden = stack.env_hidden.clone();
let redirect_stdout = call.redirect_stdout;
let redirect_stderr = call.redirect_stderr;
let mut input_iter = input.into_iter();
let (off, start_val) = if let Some(val) = fold {
(0, val)
} else if let Some(val) = input_iter.next() {
(1, val)
} else {
return Err(ShellError::GenericError(
"Expected input".to_string(),
"needs input".to_string(),
Some(span),
None,
Vec::new(),
));
};
let mut acc = if numbered {
Value::Record {
cols: vec!["index".to_string(), "item".to_string()],
vals: vec![Value::Int { val: 0, span }, start_val],
span,
}
} else {
start_val
};
let mut input_iter = input_iter
.enumerate()
.map(|(idx, x)| {
if numbered {
(
idx,
Value::Record {
cols: vec!["index".to_string(), "item".to_string()],
vals: vec![
Value::Int {
val: idx as i64 + off,
span,
},
x,
],
span,
},
)
} else {
(idx, x)
}
})
.peekable();
while let Some((idx, x)) = input_iter.next() {
stack.with_env(&orig_env_vars, &orig_env_hidden);
if let Some(var) = block.signature.get_positional(0) {
if let Some(var_id) = &var.var_id {
stack.add_var(*var_id, x);
}
}
if let Some(var) = block.signature.get_positional(1) {
if let Some(var_id) = &var.var_id {
acc = if numbered {
if let Value::Record { .. } = &acc {
acc
} else {
Value::Record {
cols: vec!["index".to_string(), "item".to_string()],
vals: vec![
Value::Int {
val: idx as i64 + off,
span,
},
acc,
],
span,
}
}
} else {
acc
};
stack.add_var(*var_id, acc);
}
}
acc = eval_block(
engine_state,
&mut stack,
block,
PipelineData::new(span),
redirect_stdout || input_iter.peek().is_some(),
redirect_stderr,
)?
.into_value(span);
if let Some(ctrlc) = &ctrlc {
if ctrlc.load(Ordering::SeqCst) {
break;
}
}
}
Ok(acc.with_span(span).into_pipeline_data())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Reduce {})
}
}