mirror of
https://github.com/nushell/nushell.git
synced 2025-08-09 06:55:36 +02:00
Allow tables and records as input to math commands (#11496)
# Description The math functions `avg`, `max`, `median`, `min`, `product`, `stddev`, `sum` and `variance` all takes a list as input and return a number. <https://github.com/nushell/nushell/blob/main/crates/nu-command/src/math/utils.rs> contains code that makes these functions work for tables (by running the function on each column), but this functionality has not been accessible because the input types are too strict. This PR remedies this. The functions should also work on records, since a record is basically a one-row table. Most of these functions also make sense for durations and file sizes, except `product` of course. There's an implementation issue with `stddev` and `variance` for durations and file sizes, but they could in principle support it. # User-Facing Changes This PR only adds supported types, and doesn't remove any, so there should be no breaking changes.
This commit is contained in:
@ -2,7 +2,9 @@ use crate::math::reducers::{reducer_for, Reduce};
|
||||
use crate::math::utils::run_with_function;
|
||||
use nu_protocol::ast::Call;
|
||||
use nu_protocol::engine::{Command, EngineState, Stack};
|
||||
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Span, Type, Value};
|
||||
use nu_protocol::{
|
||||
record, Category, Example, PipelineData, ShellError, Signature, Span, Type, Value,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SubCommand;
|
||||
@ -14,7 +16,13 @@ impl Command for SubCommand {
|
||||
|
||||
fn signature(&self) -> Signature {
|
||||
Signature::build("math product")
|
||||
.input_output_types(vec![(Type::List(Box::new(Type::Number)), Type::Number)])
|
||||
.input_output_types(vec![
|
||||
(Type::List(Box::new(Type::Number)), Type::Number),
|
||||
(Type::Range, Type::Number),
|
||||
(Type::Table(vec![]), Type::Record(vec![])),
|
||||
(Type::Record(vec![]), Type::Record(vec![])),
|
||||
])
|
||||
.allow_variants_without_examples(true)
|
||||
.category(Category::Math)
|
||||
}
|
||||
|
||||
@ -37,11 +45,21 @@ impl Command for SubCommand {
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<Example> {
|
||||
vec![Example {
|
||||
description: "Compute the product of a list of numbers",
|
||||
example: "[2 3 3 4] | math product",
|
||||
result: Some(Value::test_int(72)),
|
||||
}]
|
||||
vec![
|
||||
Example {
|
||||
description: "Compute the product of a list of numbers",
|
||||
example: "[2 3 3 4] | math product",
|
||||
result: Some(Value::test_int(72)),
|
||||
},
|
||||
Example {
|
||||
description: "Compute the product of each column in a table",
|
||||
example: "[[a b]; [1 2] [3 4]] | math product",
|
||||
result: Some(Value::test_record(record! {
|
||||
"a" => Value::test_int(3),
|
||||
"b" => Value::test_int(8),
|
||||
})),
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user