diff --git a/src/nodes/mod.rs b/src/nodes/mod.rs index da7c34e..d8e05d9 100644 --- a/src/nodes/mod.rs +++ b/src/nodes/mod.rs @@ -4,7 +4,7 @@ use std::fmt::{Debug, Display}; -use rug::Float; +use rug::{Assign, Float}; mod eval; pub mod parse; @@ -53,6 +53,14 @@ impl Display for Node { Debug::fmt(&self, f) } } +impl From for Node +where + Float: Assign, +{ + fn from(value: T) -> Self { + Self::Number(Float::with_val(PREC, value)) + } +} #[derive(Debug, Default, Copy, Clone, PartialEq)] pub enum Operator { diff --git a/src/nodes/parse.rs b/src/nodes/parse.rs index 68e6fcc..22a0518 100644 --- a/src/nodes/parse.rs +++ b/src/nodes/parse.rs @@ -8,12 +8,12 @@ use crate::nodes::{Function, Node, Nodes, Operator, PREC}; impl Node { fn from_name(s: &str) -> Result { Ok(match s { - "c" => Self::Number(Float::with_val(PREC, 299_792_458)), - "A" => Self::Number(Float::with_val(PREC, 6.02214076e23)), - "pi" => Self::Number(Float::with_val(PREC, f64::consts::PI)), + "c" => Self::from(299_792_458), + "A" => Self::from(6.02214076e23), + "pi" => Self::from(f64::consts::PI), // Planck's constant, in J*s (joule-seconds) - "h" => Self::Number(Float::with_val(PREC, 6.62607015e-34)), - "e" => Self::Number(Float::with_val(PREC, f64::consts::E)), + "h" => Self::from(6.62607015e-34), + "e" => Self::from(f64::consts::E), _ => Self::Function(s.parse()?), }) } @@ -203,10 +203,10 @@ fn test() { &[ Node::Function(Function::Sine), Node::ParenthesisStart, - Node::Number(Float::with_val(PREC, 2)), + Node::from(2), Node::ParenthesisEnd, Node::Operator(Operator::Plus), - Node::Number(Float::with_val(PREC, 1)) + Node::from(1), ], ) } @@ -215,11 +215,11 @@ fn test_e() { assert_eq!( Nodes::from_str("5e * 5").unwrap().as_ref(), &[ - Node::Number(Float::with_val(PREC, 5)), + Node::from(5), Node::Operator(Operator::Mult), - Node::Number(Float::with_val(PREC, f64::consts::E)), + Node::from(f64::consts::E), Node::Operator(Operator::Mult), - Node::Number(Float::with_val(PREC, 5)) + Node::from(5), ], ) }