diff --git a/src/nodes/eval.rs b/src/nodes/eval.rs index d587064..b25d3d9 100644 --- a/src/nodes/eval.rs +++ b/src/nodes/eval.rs @@ -41,6 +41,29 @@ fn collapse_toplevel(nodes: &mut Vec, mut end: usize) -> Result<(), Error> .rposition(|n| *n == Node::ParenthesisStart) .unwrap_or(0); + while let Some((index, function)) = nodes[start..end] + .iter() + .enumerate() + .filter_map(|(i, n)| match n { + Node::Function(f) => Some((i, *f)), + _ => None, + }) + .next() + { + let Some(node) = nodes.get_mut(start + index + 1) else { + return Err(Error::OutOfBounds(Nodes(nodes.clone()), start + index + 1)); + }; + + let Node::Number(n) = node else { + return Err(Error::MissingArgument(node.clone())); + }; + + function.apply_to(n); + + nodes.remove(start + index); + end -= 1; + } + let mut i = start; while i < end { if let Node::Operator(operator) = nodes[i] @@ -66,29 +89,6 @@ fn collapse_toplevel(nodes: &mut Vec, mut end: usize) -> Result<(), Error> i += 1; } - while let Some((index, function)) = nodes[start..end] - .iter() - .enumerate() - .filter_map(|(i, n)| match n { - Node::Function(f) => Some((i, *f)), - _ => None, - }) - .next() - { - let Some(node) = nodes.get_mut(start + index + 1) else { - return Err(Error::OutOfBounds(Nodes(nodes.clone()), start + index + 1)); - }; - - let Node::Number(n) = node else { - return Err(Error::MissingArgument(node.clone())); - }; - - function.apply_to(n); - - nodes.remove(start + index); - end -= 1; - } - macro_rules! collapse_operator { ($operator:expr) => { while let Some(index) = nodes[start..end] diff --git a/src/nodes/tests.rs b/src/nodes/tests.rs index e5a6a68..403ea3d 100644 --- a/src/nodes/tests.rs +++ b/src/nodes/tests.rs @@ -73,3 +73,8 @@ fn abs() { fn factorial() { assert_eq!(eval("factorial(3)"), 6.); } + +#[test] +fn negative_fn() { + assert_eq!(eval("-sin(pi)"), 0.); +}