expression-plus 1.0.1

Simple expression evaluator


To use this package, run the following command in your project's root directory:

Manual usage
Put the following dependency into your project's dependences section:

Simple expression evaluator

Supports +, -, *, /, (), >, >=, ==, !=, <=, <, ?:, variables and functions.

import std.stdio;
import std.math;

import expression;

void main() {
    auto expr = compileExpression("base + delta/(0.5 * begin - end) + sqrt(min(base / 10, delta))");

    static assert(is(typeof(expr) == Expression!float));

    // set variables and functions as properties
    expr.base = 1001.3;
    expr.delta = 535.4;
    expr.min = (float x, float y) => x < y ? x : y;

    // or as indexes
    expr["begin"] = 34;
    expr["end"] = 12;
    expr["sqrt"] = (float x) => sqrt(x);

    // evaluate
    writeln("result: ", expr()); // 1118.39

    // functions with different arities may have the same name
    expr = compileExpression("dist(x, y) + dist(x)");
    expr.dist = (float x, float y) => sqrt(x*x + y*y);
    expr.dist = (float x) => sqrt((x + 2) * (x + 2) + (x + 9) * (x + 9));
    expr.x = 3;
    expr.y = 4;

    writeln("result: ", expr()); // 18

    // integer type
    int expr2(string source) {
        auto e = compileExpression!int(source);
        e.a = 3;
        e.b = -1;
        e.s = (int x) => x*x;
        return e();
    }

    assert(expr2("((a - 3) * b + 1) * s(b - 1)") == 5);
}
Authors:
  • Jack Applegame
Dependencies:
none
Versions:
1.0.1 2024-Oct-09
~master 2024-Oct-09
Show all 2 versions
Download Stats:
  • 0 downloads today

  • 0 downloads this week

  • 0 downloads this month

  • 2 downloads total

Score:
0.1
Short URL:
expression-plus.dub.pm