cratification: part II of the math commands to nu-cmd-extra (#9657)

The following math commands are being moved to nu-cmd-extra

* cos
* cosh
* egamma
* phi
* pi
* sin
* sinh
* tan
* tanh
* tau

For now I think we have most of the obvious commands moved over based on

@sholderbach this should cover moving the "high school" commands..

>>Yeah I think this rough separation into "high school" math in extra
and "middle school"/"programmer" math in the core makes a ton of sense.

And to reference the @fdncred list from
https://github.com/nushell/nushell/pull/9647#issuecomment-1629498812
This commit is contained in:
Michael Angerman
2023-07-11 11:23:39 -07:00
committed by GitHub
parent e10d84b72f
commit 942c66a9f3
16 changed files with 52 additions and 34 deletions

View File

@ -327,14 +327,6 @@ pub fn add_shell_command_context(mut engine_state: EngineState) -> EngineState {
MathStddev,
MathSum,
MathVariance,
MathSin,
MathCos,
MathTan,
MathSinH,
MathCosH,
MathTanH,
MathPi,
MathTau,
MathEuler,
MathExp,
MathLn,

View File

@ -9,9 +9,9 @@ pub fn test_examples(cmd: impl Command + 'static) {
#[cfg(test)]
mod test_examples {
use super::super::{
Ansi, Date, Enumerate, Flatten, From, Get, Into, IntoString, Math, MathEuler, MathPi,
MathRound, ParEach, Path, PathParse, Random, Sort, SortBy, Split, SplitColumn, SplitRow,
Str, StrJoin, StrLength, StrReplace, Update, Url, Values, Wrap,
Ansi, Date, Enumerate, Flatten, From, Get, Into, IntoString, Math, MathEuler, MathRound,
ParEach, Path, PathParse, Random, Sort, SortBy, Split, SplitColumn, SplitRow, Str, StrJoin,
StrLength, StrReplace, Update, Url, Values, Wrap,
};
use crate::{Each, To};
use nu_cmd_lang::example_support::{
@ -80,7 +80,6 @@ mod test_examples {
working_set.add_decl(Box::new(Let));
working_set.add_decl(Box::new(Math));
working_set.add_decl(Box::new(MathEuler));
working_set.add_decl(Box::new(MathPi));
working_set.add_decl(Box::new(MathRound));
working_set.add_decl(Box::new(Mut));
working_set.add_decl(Box::new(Path));

View File

@ -1,111 +0,0 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Span, Type, Value};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"math cos"
}
fn signature(&self) -> Signature {
Signature::build("math cos")
.switch("degrees", "Use degrees instead of radians", Some('d'))
.input_output_types(vec![(Type::Number, Type::Float)])
.vectorizes_over_list(true)
.category(Category::Math)
}
fn usage(&self) -> &str {
"Returns the cosine of the number."
}
fn search_terms(&self) -> Vec<&str> {
vec!["trigonometry"]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let use_degrees = call.has_flag("degrees");
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
input.map(
move |value| operate(value, head, use_degrees),
engine_state.ctrlc.clone(),
)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Apply the cosine to π",
example: "math pi | math cos",
result: Some(Value::test_float(-1f64)),
},
Example {
description: "Apply the cosine to a list of angles in degrees",
example: "[0 90 180 270 360] | math cos -d",
result: Some(Value::List {
vals: vec![
Value::test_float(1f64),
Value::test_float(0f64),
Value::test_float(-1f64),
Value::test_float(0f64),
Value::test_float(1f64),
],
span: Span::test_data(),
}),
},
]
}
}
fn operate(value: Value, head: Span, use_degrees: bool) -> Value {
match value {
numeric @ (Value::Int { .. } | Value::Float { .. }) => {
let (val, span) = match numeric {
Value::Int { val, span } => (val as f64, span),
Value::Float { val, span } => (val, span),
_ => unreachable!(),
};
let val = if use_degrees { val.to_radians() } else { val };
Value::Float {
val: val.cos(),
span,
}
}
Value::Error { .. } => value,
other => Value::Error {
error: Box::new(ShellError::OnlySupportsThisInputType {
exp_input_type: "numeric".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.expect_span(),
}),
},
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -1,92 +0,0 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Span, Type, Value};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"math cosh"
}
fn signature(&self) -> Signature {
Signature::build("math cosh")
.input_output_types(vec![(Type::Number, Type::Float)])
.vectorizes_over_list(true)
.category(Category::Math)
}
fn usage(&self) -> &str {
"Returns the hyperbolic cosine of the number."
}
fn search_terms(&self) -> Vec<&str> {
vec!["trigonometry", "hyperbolic"]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
input.map(
move |value| operate(value, head),
engine_state.ctrlc.clone(),
)
}
fn examples(&self) -> Vec<Example> {
let e = std::f64::consts::E;
vec![Example {
description: "Apply the hyperbolic cosine to 1",
example: "1 | math cosh",
result: Some(Value::test_float(((e * e) + 1.0) / (2.0 * e))),
}]
}
}
fn operate(value: Value, head: Span) -> Value {
match value {
numeric @ (Value::Int { .. } | Value::Float { .. }) => {
let (val, span) = match numeric {
Value::Int { val, span } => (val as f64, span),
Value::Float { val, span } => (val, span),
_ => unreachable!(),
};
Value::Float {
val: val.cosh(),
span,
}
}
Value::Error { .. } => value,
other => Value::Error {
error: Box::new(ShellError::OnlySupportsThisInputType {
exp_input_type: "numeric".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.expect_span(),
}),
},
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -1,64 +0,0 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Type, Value,
};
#[allow(clippy::excessive_precision)]
/// The Euler-Mascheroni constant (γ)
pub const EGAMMA: f64 = 0.577215664901532860606512090082402431_f64;
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"math egamma"
}
fn signature(&self) -> Signature {
Signature::build("math egamma")
.input_output_types(vec![(Type::Any, Type::Float)])
.category(Category::Math)
}
fn usage(&self) -> &str {
"Returns the EulerMascheroni constant γ. ( 1 | math egamma)."
}
fn search_terms(&self) -> Vec<&str> {
vec!["euler", "constant", "gamma"]
}
#[allow(clippy::approx_constant)]
fn examples(&self) -> Vec<Example> {
vec![Example {
example: "math egamma | math round --precision 3",
description: "Get the first three decimal digits of γ",
result: Some(Value::test_float(0.577)),
}]
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
// TODO: replace with std::f64::consts::EGAMMA when available https://github.com/rust-lang/rust/issues/103883
Ok(Value::float(EGAMMA, call.head).into_pipeline_data())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -1,9 +1,6 @@
mod abs;
mod avg;
mod ceil;
mod cos;
mod cosh;
mod egamma;
mod euler;
mod exp;
mod floor;
@ -14,19 +11,12 @@ mod max;
mod median;
mod min;
mod mode;
mod phi;
mod pi;
mod product;
mod reducers;
mod round;
mod sin;
mod sinh;
mod sqrt;
mod stddev;
mod sum;
mod tan;
mod tanh;
mod tau;
mod utils;
mod variance;
@ -46,18 +36,7 @@ pub use stddev::SubCommand as MathStddev;
pub use sum::SubCommand as MathSum;
pub use variance::SubCommand as MathVariance;
pub use cos::SubCommand as MathCos;
pub use cosh::SubCommand as MathCosH;
pub use sin::SubCommand as MathSin;
pub use sinh::SubCommand as MathSinH;
pub use tan::SubCommand as MathTan;
pub use tanh::SubCommand as MathTanH;
pub use egamma::SubCommand as MathEulerGamma;
pub use euler::SubCommand as MathEuler;
pub use phi::SubCommand as MathPhi;
pub use pi::SubCommand as MathPi;
pub use tau::SubCommand as MathTau;
pub use self::log::SubCommand as MathLog;
pub use exp::SubCommand as MathExp;

View File

@ -1,64 +0,0 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Type, Value,
};
#[allow(clippy::excessive_precision)]
/// The golden ratio (φ)
pub const PHI: f64 = 1.618033988749894848204586834365638118_f64;
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"math phi"
}
fn signature(&self) -> Signature {
Signature::build("math phi")
.input_output_types(vec![(Type::Any, Type::Float)])
.category(Category::Math)
}
fn usage(&self) -> &str {
"Returns the golden ratio φ. ( (1 + sqrt(5) ) / 2 )"
}
fn search_terms(&self) -> Vec<&str> {
vec!["golden", "ratio", "constant"]
}
#[allow(clippy::approx_constant)]
fn examples(&self) -> Vec<Example> {
vec![Example {
example: "math phi | math round --precision 3",
description: "Get the first two decimal digits of φ",
result: Some(Value::test_float(1.618)),
}]
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
// TODO: replace with std::f64::consts::PHI when available https://github.com/rust-lang/rust/issues/103883
Ok(Value::float(PHI, call.head).into_pipeline_data())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -1,59 +0,0 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Type, Value,
};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"math pi"
}
fn signature(&self) -> Signature {
Signature::build("math pi")
.input_output_types(vec![(Type::Any, Type::Float)])
.category(Category::Math)
}
fn usage(&self) -> &str {
"Returns the mathematical constant π."
}
fn search_terms(&self) -> Vec<&str> {
vec!["trigonometry", "constant"]
}
#[allow(clippy::approx_constant)]
fn examples(&self) -> Vec<Example> {
vec![Example {
example: "math pi | math round --precision 2",
description: "Get the first two decimal digits of π",
result: Some(Value::test_float(3.14)),
}]
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(Value::float(std::f64::consts::PI, call.head).into_pipeline_data())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -1,111 +0,0 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Span, Type, Value};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"math sin"
}
fn signature(&self) -> Signature {
Signature::build("math sin")
.switch("degrees", "Use degrees instead of radians", Some('d'))
.input_output_types(vec![(Type::Number, Type::Float)])
.vectorizes_over_list(true)
.category(Category::Math)
}
fn usage(&self) -> &str {
"Returns the sine of the number."
}
fn search_terms(&self) -> Vec<&str> {
vec!["trigonometry"]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let use_degrees = call.has_flag("degrees");
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
input.map(
move |value| operate(value, head, use_degrees),
engine_state.ctrlc.clone(),
)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Apply the sine to π/2",
example: "(math pi) / 2 | math sin",
result: Some(Value::test_float(1f64)),
},
Example {
description: "Apply the sine to a list of angles in degrees",
example: "[0 90 180 270 360] | math sin -d | math round --precision 4",
result: Some(Value::List {
vals: vec![
Value::test_float(0f64),
Value::test_float(1f64),
Value::test_float(0f64),
Value::test_float(-1f64),
Value::test_float(0f64),
],
span: Span::test_data(),
}),
},
]
}
}
fn operate(value: Value, head: Span, use_degrees: bool) -> Value {
match value {
numeric @ (Value::Int { .. } | Value::Float { .. }) => {
let (val, span) = match numeric {
Value::Int { val, span } => (val as f64, span),
Value::Float { val, span } => (val, span),
_ => unreachable!(),
};
let val = if use_degrees { val.to_radians() } else { val };
Value::Float {
val: val.sin(),
span,
}
}
Value::Error { .. } => value,
other => Value::Error {
error: Box::new(ShellError::OnlySupportsThisInputType {
exp_input_type: "numeric".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.expect_span(),
}),
},
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -1,92 +0,0 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Span, Type, Value};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"math sinh"
}
fn signature(&self) -> Signature {
Signature::build("math sinh")
.input_output_types(vec![(Type::Number, Type::Float)])
.vectorizes_over_list(true)
.category(Category::Math)
}
fn usage(&self) -> &str {
"Returns the hyperbolic sine of the number."
}
fn search_terms(&self) -> Vec<&str> {
vec!["trigonometry", "hyperbolic"]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
input.map(
move |value| operate(value, head),
engine_state.ctrlc.clone(),
)
}
fn examples(&self) -> Vec<Example> {
let e = std::f64::consts::E;
vec![Example {
description: "Apply the hyperbolic sine to 1",
example: "1 | math sinh",
result: Some(Value::test_float((e * e - 1.0) / (2.0 * e))),
}]
}
}
fn operate(value: Value, head: Span) -> Value {
match value {
numeric @ (Value::Int { .. } | Value::Float { .. }) => {
let (val, span) = match numeric {
Value::Int { val, span } => (val as f64, span),
Value::Float { val, span } => (val, span),
_ => unreachable!(),
};
Value::Float {
val: val.sinh(),
span,
}
}
Value::Error { .. } => value,
other => Value::Error {
error: Box::new(ShellError::OnlySupportsThisInputType {
exp_input_type: "numeric".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.expect_span(),
}),
},
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -1,109 +0,0 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Span, Type, Value};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"math tan"
}
fn signature(&self) -> Signature {
Signature::build("math tan")
.switch("degrees", "Use degrees instead of radians", Some('d'))
.input_output_types(vec![(Type::Number, Type::Float)])
.vectorizes_over_list(true)
.category(Category::Math)
}
fn usage(&self) -> &str {
"Returns the tangent of the number."
}
fn search_terms(&self) -> Vec<&str> {
vec!["trigonometry"]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let use_degrees = call.has_flag("degrees");
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
input.map(
move |value| operate(value, head, use_degrees),
engine_state.ctrlc.clone(),
)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Apply the tangent to π/4",
example: "(math pi) / 4 | math tan",
result: Some(Value::test_float(1f64)),
},
Example {
description: "Apply the tangent to a list of angles in degrees",
example: "[-45 0 45] | math tan -d",
result: Some(Value::List {
vals: vec![
Value::test_float(-1f64),
Value::test_float(0f64),
Value::test_float(1f64),
],
span: Span::test_data(),
}),
},
]
}
}
fn operate(value: Value, head: Span, use_degrees: bool) -> Value {
match value {
numeric @ (Value::Int { .. } | Value::Float { .. }) => {
let (val, span) = match numeric {
Value::Int { val, span } => (val as f64, span),
Value::Float { val, span } => (val, span),
_ => unreachable!(),
};
let val = if use_degrees { val.to_radians() } else { val };
Value::Float {
val: val.tan(),
span,
}
}
Value::Error { .. } => value,
other => Value::Error {
error: Box::new(ShellError::OnlySupportsThisInputType {
exp_input_type: "numeric".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.expect_span(),
}),
},
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -1,91 +0,0 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Span, Type, Value};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"math tanh"
}
fn signature(&self) -> Signature {
Signature::build("math tanh")
.input_output_types(vec![(Type::Number, Type::Float)])
.vectorizes_over_list(true)
.category(Category::Math)
}
fn usage(&self) -> &str {
"Returns the hyperbolic tangent of the number."
}
fn search_terms(&self) -> Vec<&str> {
vec!["trigonometry", "hyperbolic"]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
input.map(
move |value| operate(value, head),
engine_state.ctrlc.clone(),
)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Apply the hyperbolic tangent to 10*π",
example: "(math pi) * 10 | math tanh",
result: Some(Value::test_float(1f64)),
}]
}
}
fn operate(value: Value, head: Span) -> Value {
match value {
numeric @ (Value::Int { .. } | Value::Float { .. }) => {
let (val, span) = match numeric {
Value::Int { val, span } => (val as f64, span),
Value::Float { val, span } => (val, span),
_ => unreachable!(),
};
Value::Float {
val: val.tanh(),
span,
}
}
Value::Error { .. } => value,
other => Value::Error {
error: Box::new(ShellError::OnlySupportsThisInputType {
exp_input_type: "numeric".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.expect_span(),
}),
},
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -1,59 +0,0 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Type, Value,
};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"math tau"
}
fn signature(&self) -> Signature {
Signature::build("math tau")
.input_output_types(vec![(Type::Any, Type::Float)])
.category(Category::Math)
}
fn usage(&self) -> &str {
"Returns the mathematical constant τ."
}
fn search_terms(&self) -> Vec<&str> {
vec!["trigonometry", "constant"]
}
#[allow(clippy::approx_constant)]
fn examples(&self) -> Vec<Example> {
vec![Example {
example: "math tau | math round --precision 2",
description: "Get the first two decimal digits of τ",
result: Some(Value::test_float(6.28)),
}]
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(Value::float(std::f64::consts::TAU, call.head).into_pipeline_data())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}