2

I'm using Ncalc in my new project and it already has almost everything I need .

I said almost everything, because now I need to expand some functions and also add new ones such as : nth root,random, etc

Do you know if anyone has already implemented those functions? Or could you give me any tips or guides to extend the function list of Ncalc???

Thanks in advance.

eddy
  • 4,373
  • 16
  • 60
  • 94

1 Answers1

10

If I understand correctly:

As much as I was using it is by creating a static function

private static void NCalcExtensionFunctions(string name, FunctionArgs functionArgs)
{
    if (name == "yourfunctionname")
    {
        var param1 = functionArgs.Parameters[0].Evaluate();
        var param2 = functionArgs.Parameters[1].Evaluate();
        //... as many params as you require
        functionArgs.Result = (int)param1 * (int)param2; //do your own function logic here
    }
    if (name == "random")
    {
        if(functionArgs.Parameters.Count() == 0) 
        {
            functionArgs.Result = new Random().Next();
        }
        else if(functionArgs.Parameters.Count() == 1) 
        {
            functionArgs.Result = new Random().Next((int)functionArgs.Parameters[0].Evaluate());
        }
        else 
        {
            functionArgs.Result = new Random().Next((int)functionArgs.Parameters[0].Evaluate(), (int)functionArgs.Parameters[1].Evaluate());
        }
    }
}

And then you use it as follows

var expr = new Expression("yourfunctionname(3, 2)");
expr.EvaluateFunction += NCalcExtensionFunctions;
var result = expr.Evaluate();

var randExpr = new Expression("random(100)"); 
randExpr.EvaluateFunction += NCalcExtensionFunctions;
var resultRand = randExpr.Evaluate();

I hope I didn't mistype any of the code. A list of NCalc built-in functions can be found here: http://ncalc.codeplex.com/wikipage?title=functions&referringTitle=Home

Gomiunik
  • 410
  • 4
  • 11
  • Do you know if it's possible to set a custom error message in the custom function definition. If say for example the parameters are invalid for that function. – Fred Aug 02 '18 at 12:59
  • 1
    Not that I would know. I'd handle this with exceptions. – Gomiunik Aug 03 '18 at 18:29