refactor: impl From for Node to easily insert constants
this is mostly useful for tests and in Node::from_name
This commit is contained in:
parent
d8dc549954
commit
69bf8f4635
2 changed files with 19 additions and 11 deletions
|
|
@ -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<T> From<T> for Node
|
||||
where
|
||||
Float: Assign<T>,
|
||||
{
|
||||
fn from(value: T) -> Self {
|
||||
Self::Number(Float::with_val(PREC, value))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Copy, Clone, PartialEq)]
|
||||
pub enum Operator {
|
||||
|
|
|
|||
|
|
@ -8,12 +8,12 @@ use crate::nodes::{Function, Node, Nodes, Operator, PREC};
|
|||
impl Node {
|
||||
fn from_name(s: &str) -> Result<Self, String> {
|
||||
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),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue