nu_cmd_extra/extra/math/
exp.rs1use nu_engine::command_prelude::*;
2
3#[derive(Clone)]
4pub struct MathExp;
5
6impl Command for MathExp {
7 fn name(&self) -> &str {
8 "math exp"
9 }
10
11 fn signature(&self) -> Signature {
12 Signature::build("math exp")
13 .input_output_types(vec![
14 (Type::Number, Type::Float),
15 (
16 Type::List(Box::new(Type::Number)),
17 Type::List(Box::new(Type::Float)),
18 ),
19 ])
20 .allow_variants_without_examples(true)
21 .category(Category::Math)
22 }
23
24 fn description(&self) -> &str {
25 "Returns e raised to the power of x."
26 }
27
28 fn search_terms(&self) -> Vec<&str> {
29 vec!["exponential", "exponentiation", "euler"]
30 }
31
32 fn run(
33 &self,
34 engine_state: &EngineState,
35 _stack: &mut Stack,
36 call: &Call,
37 input: PipelineData,
38 ) -> Result<PipelineData, ShellError> {
39 let head = call.head;
40 if let PipelineData::Empty = input {
42 return Err(ShellError::PipelineEmpty { dst_span: head });
43 }
44 input.map(move |value| operate(value, head), engine_state.signals())
45 }
46
47 fn examples(&self) -> Vec<Example<'_>> {
48 vec![
49 Example {
50 description: "Get e raised to the power of zero",
51 example: "0 | math exp",
52 result: Some(Value::test_float(1.0f64)),
53 },
54 Example {
55 description: "Get e (same as 'math e')",
56 example: "1 | math exp",
57 result: Some(Value::test_float(1.0f64.exp())),
58 },
59 ]
60 }
61}
62
63fn operate(value: Value, head: Span) -> Value {
64 match value {
65 numeric @ (Value::Int { .. } | Value::Float { .. }) => {
66 let span = numeric.span();
67 let (val, span) = match numeric {
68 Value::Int { val, .. } => (val as f64, span),
69 Value::Float { val, .. } => (val, span),
70 _ => unreachable!(),
71 };
72
73 Value::float(val.exp(), span)
74 }
75 Value::Error { .. } => value,
76 other => Value::error(
77 ShellError::OnlySupportsThisInputType {
78 exp_input_type: "numeric".into(),
79 wrong_type: other.get_type().to_string(),
80 dst_span: head,
81 src_span: other.span(),
82 },
83 head,
84 ),
85 }
86}
87
88#[cfg(test)]
89mod test {
90 use super::*;
91
92 #[test]
93 fn test_examples() {
94 use crate::test_examples;
95
96 test_examples(MathExp {})
97 }
98}