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:
electria 2026-11-13 16:02:22 -08:00
commit dc6bdcf3ac
Signed by: electria
SSH key fingerprint: SHA256:8LlB3ucPbBHqozqkhsNbaV5oG3SlzzqUj8FZDL6IPQs
4 changed files with 22 additions and 1 deletions

View file

@ -1,6 +1,6 @@
use rug::{ use rug::{
Float, Float,
ops::{AddFrom, DivFrom, MulFrom, PowFrom, SubFrom}, ops::{AddFrom, CompleteRound, DivFrom, MulFrom, PowFrom, SubFrom},
}; };
use crate::nodes::{Function, Node, Nodes, Operator}; use crate::nodes::{Function, Node, Nodes, Operator};
@ -143,6 +143,18 @@ impl Function {
match self { match self {
Self::AbsoluteValue => Float::abs_mut(n), 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::SquareRoot => Float::sqrt_mut(n),
Self::LogNatural => Float::ln_mut(n), Self::LogNatural => Float::ln_mut(n),

View file

@ -76,6 +76,8 @@ pub enum Operator {
pub enum Function { pub enum Function {
AbsoluteValue, AbsoluteValue,
Factorial,
SquareRoot, SquareRoot,
LogNatural, LogNatural,

View file

@ -40,6 +40,8 @@ impl FromStr for Function {
match s { match s {
"abs" => Ok(Self::AbsoluteValue), "abs" => Ok(Self::AbsoluteValue),
"factorial" => Ok(Self::Factorial),
"sqrt" => Ok(Self::SquareRoot), "sqrt" => Ok(Self::SquareRoot),
"ln" => Ok(Self::LogNatural), "ln" => Ok(Self::LogNatural),

View file

@ -68,3 +68,8 @@ fn operator_after_parenthesis() {
fn abs() { fn abs() {
assert_eq!(eval("abs(-1)"), 1.); assert_eq!(eval("abs(-1)"), 1.);
} }
#[test]
fn factorial() {
assert_eq!(eval("factorial(3)"), 6.);
}