Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use symbol ! as factorial #11

Closed
totosugito opened this issue Mar 1, 2023 · 1 comment
Closed

Use symbol ! as factorial #11

totosugito opened this issue Mar 1, 2023 · 1 comment

Comments

@totosugito
Copy link

totosugito commented Mar 1, 2023

Hi,
Thank you for creating this great plugin.
I am planned to add factorial function.
Example 5! -> 1 x 2 x 3 x 4 x 5 = 120
Do you have idea how to add this new function (using ! symbol) to compute factorial.
Thank you

@ram6ler
Copy link
Owner

ram6ler commented Sep 10, 2023

Thanks for your interest in this library. Sorry for the delay in response!

I'm a little wary of adding support for factorials because they blow up so quickly and don't really fit into the context of double based numeric calculations, which this library aims at. (I have another library, dart-trotter, that uses BigInt representations of factorials and other values that come up in combinatorics so that arbitrarily large values can be handled conveniently — check it out if you're interested.)

However, we could implement this by first adding a function definition to lib/src/defs.dart:

.
.
.
/// A mapping of string representations to functions.
final Map<String, num Function(num)> oneParameterFunctionMap = {
  "abs": (num x) => x.abs(),
  .
  .
  .
  // Add this code: -----------------------------------------------------
  "fact": (num x) =>
      [for (var i = 1; i <= x; i++) i].fold<double>(1.0, (a, b) => a * b),
  // --------------------------------------------------------------- snip!
  .
  .
  .

and then replacing expressions of the form <integer>! with fact(<integer>), which can be done in the cleanExpression function in lib/src/helpers.dart, which is called before the expression is actually used to build a callable tree structure:

/// Returns a sanitized version of `expression`.
String cleanExpression(String expression) {
  final junk = RegExp(r"[^0-9a-zA-Z_.+\-/*%^(),]"),
  // Add this code: --------------------------------------
      factorial = RegExp(r"([0-9]+) *!");
  if (factorial.hasMatch(expression)) {
    expression = expression.replaceAllMapped(
        factorial, (match) => "fact(${match.group(1)!})");
  }
  // ----------------------------------------------- snip!
  .
  .
  .

Now something like

print("2 * 5!".interpret());

should work as expected.

Hope that helps! Feel free to fork and implement if it suits your needs!

@ram6ler ram6ler closed this as completed Sep 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants