feat: add factorial function
this isn't perfect, and it doesn't exist in typst, but at least it exists now. the problem is switching away from very basic operators and very basic functions requires a lot of work (many changes to both evaluation and parsing)
This commit is contained in:
parent
4ffe6c8d0f
commit
dc6bdcf3ac
4 changed files with 22 additions and 1 deletions
|
|
@ -1,6 +1,6 @@
|
|||
use rug::{
|
||||
Float,
|
||||
ops::{AddFrom, DivFrom, MulFrom, PowFrom, SubFrom},
|
||||
ops::{AddFrom, CompleteRound, DivFrom, MulFrom, PowFrom, SubFrom},
|
||||
};
|
||||
|
||||
use crate::nodes::{Function, Node, Nodes, Operator};
|
||||
|
|
@ -143,6 +143,18 @@ impl Function {
|
|||
match self {
|
||||
Self::AbsoluteValue => Float::abs_mut(n),
|
||||
|
||||
Self::Factorial => {
|
||||
if !n.is_integer() {
|
||||
eprintln!("{n} is not an integer, rounding to calculate its factorial");
|
||||
}
|
||||
|
||||
if let Some(int) = n.to_u32_saturating() {
|
||||
Float::factorial(int).complete_into(n)
|
||||
} else {
|
||||
eprintln!("{n} does not fit into a u32, unable to calculate its factorial");
|
||||
}
|
||||
}
|
||||
|
||||
Self::SquareRoot => Float::sqrt_mut(n),
|
||||
|
||||
Self::LogNatural => Float::ln_mut(n),
|
||||
|
|
|
|||
|
|
@ -76,6 +76,8 @@ pub enum Operator {
|
|||
pub enum Function {
|
||||
AbsoluteValue,
|
||||
|
||||
Factorial,
|
||||
|
||||
SquareRoot,
|
||||
|
||||
LogNatural,
|
||||
|
|
|
|||
|
|
@ -40,6 +40,8 @@ impl FromStr for Function {
|
|||
match s {
|
||||
"abs" => Ok(Self::AbsoluteValue),
|
||||
|
||||
"factorial" => Ok(Self::Factorial),
|
||||
|
||||
"sqrt" => Ok(Self::SquareRoot),
|
||||
|
||||
"ln" => Ok(Self::LogNatural),
|
||||
|
|
|
|||
|
|
@ -68,3 +68,8 @@ fn operator_after_parenthesis() {
|
|||
fn abs() {
|
||||
assert_eq!(eval("abs(-1)"), 1.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn factorial() {
|
||||
assert_eq!(eval("factorial(3)"), 6.);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue