From dc6bdcf3ac1b22de05ae6b9927d9a465b15afd72 Mon Sep 17 00:00:00 2001 From: electria Date: Fri, 13 Nov 2026 16:02:22 -0800 Subject: [PATCH] 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) --- src/nodes/eval.rs | 14 +++++++++++++- src/nodes/mod.rs | 2 ++ src/nodes/parse.rs | 2 ++ src/nodes/tests.rs | 5 +++++ 4 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/nodes/eval.rs b/src/nodes/eval.rs index f0adfaf..d587064 100644 --- a/src/nodes/eval.rs +++ b/src/nodes/eval.rs @@ -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), diff --git a/src/nodes/mod.rs b/src/nodes/mod.rs index 8970c31..50b9ffe 100644 --- a/src/nodes/mod.rs +++ b/src/nodes/mod.rs @@ -76,6 +76,8 @@ pub enum Operator { pub enum Function { AbsoluteValue, + Factorial, + SquareRoot, LogNatural, diff --git a/src/nodes/parse.rs b/src/nodes/parse.rs index c5f69e8..324d2bf 100644 --- a/src/nodes/parse.rs +++ b/src/nodes/parse.rs @@ -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), diff --git a/src/nodes/tests.rs b/src/nodes/tests.rs index 4a8b2db..e5a6a68 100644 --- a/src/nodes/tests.rs +++ b/src/nodes/tests.rs @@ -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.); +}