fix: do unary operators after function evaluation
This commit is contained in:
parent
f87bb5903f
commit
6980655714
2 changed files with 28 additions and 23 deletions
|
|
@ -41,6 +41,29 @@ fn collapse_toplevel(nodes: &mut Vec<Node>, mut end: usize) -> Result<(), Error>
|
||||||
.rposition(|n| *n == Node::ParenthesisStart)
|
.rposition(|n| *n == Node::ParenthesisStart)
|
||||||
.unwrap_or(0);
|
.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;
|
let mut i = start;
|
||||||
while i < end {
|
while i < end {
|
||||||
if let Node::Operator(operator) = nodes[i]
|
if let Node::Operator(operator) = nodes[i]
|
||||||
|
|
@ -66,29 +89,6 @@ fn collapse_toplevel(nodes: &mut Vec<Node>, mut end: usize) -> Result<(), Error>
|
||||||
i += 1;
|
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 {
|
macro_rules! collapse_operator {
|
||||||
($operator:expr) => {
|
($operator:expr) => {
|
||||||
while let Some(index) = nodes[start..end]
|
while let Some(index) = nodes[start..end]
|
||||||
|
|
|
||||||
|
|
@ -73,3 +73,8 @@ fn abs() {
|
||||||
fn factorial() {
|
fn factorial() {
|
||||||
assert_eq!(eval("factorial(3)"), 6.);
|
assert_eq!(eval("factorial(3)"), 6.);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn negative_fn() {
|
||||||
|
assert_eq!(eval("-sin(pi)"), 0.);
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue