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

How to cast(or convert) to some type ? #77

Open
Himmelt opened this issue Dec 26, 2023 · 1 comment
Open

How to cast(or convert) to some type ? #77

Himmelt opened this issue Dec 26, 2023 · 1 comment
Labels
Help/Question A question the answer to which may help other users in the future

Comments

@Himmelt
Copy link

Himmelt commented Dec 26, 2023

Hello!

Dictionary<string, Func<object>> varMap = new() {
    ["sec"] = () => DateTime.Now.Second
};

var calc = Funny.WithFunction("vars", (string name) => varMap[name]()).BuildForCalcConstant();

var result = calc.Calc("1 + vars('sec')");

Console.WriteLine(result);

These codes will cause NFun.Exceptions.FunnyParseException:“Invalid operator call argument: +(T0, T0)->T0. Expected: T0”.

I want to cast or convert the object{int} type to integer or real type, but I didn't found the usage in the examples.

Can you show me how to do this ?

Thanks !

@tmteam
Copy link
Owner

tmteam commented Dec 26, 2023

Hi! As i see here - the func in the dictionary returns object, that means that vars function returns any type (object, in terms of C#)

But as far as Nfun has strict type system - it denies to sum any and number item, so you have the error.

to show it more clearly - lets simplify your code (in terms of types) like this:

var calc = Funny.WithFunction<string, object> ("vars", (string name) => new object()).BuildForCalcConstant();
var result = calc.Calc("1 + vars('sec')"); 

here you can see, that it is impossible to sum 1 and new object().

so, the solution is to change Func<object> to Func<int>:

        Dictionary<string, Func<int>> varMap = new() {
            ["sec"] = () => DateTime.Now.Second
        };
        var calc = Funny.WithFunction("vars", (string name) => varMap[name]()).BuildForCalcConstant();
        var result = calc.Calc("1 + vars('sec')");
        Console.WriteLine(result);

or to use named typed function:

        var calc = Funny.WithFunction("sec", () => DateTime.Now.Second).BuildForCalcConstant();
        var result = calc.Calc("1 + sec()");
        Console.WriteLine(result);

@tmteam tmteam added the Help/Question A question the answer to which may help other users in the future label Dec 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Help/Question A question the answer to which may help other users in the future
Projects
None yet
Development

No branches or pull requests

2 participants