Home > Mobile >  Can you store an operation as a variable?
Can you store an operation as a variable?

Time:05-19

I'm working on a calculator and I would like to allow the user to input what operation they want to use. But I need to be able to store that as a variable so it can be used later. The problem is that I don't know what variable type I would store it as and how I would use it between two other variables so the program treats it as a mathematical operation.

The variables I have are x, y, and op, so would I do something like x(op)y or x op y? Or are both of those wrong?

Thanks for any feedback!

CodePudding user response:

It depends on what your exact requirements are, but I would suggest creating a class:

public class Operation  {

    // Stores the RHS value
    public decimal Right { get; set; }

    // Stores the LHS value
    public decimal Left { get; set; }

    // Stores the operator ' ', '-', '*', '/'
    // for ease-of-printing
    public char Operation { get; set; }

    // Stores the actual code object that will give the result
    public Func<decimal, decimal, decimal> Function { get; set; }
}

With this setup, you can including parsing logic and print logic while allowing your program to work with the data itself more easily. Of course, you could also create a grammar, combine that with a lexer and parser to get the output and then all you'd need to store would be the string variable itself (see here). Even with that approach, however, you'd want to store this information to avoid processing it multiple times.

CodePudding user response:

Yes, you can assign to the buttons of your calculator ( ,-,,/) to give to the variable "op" the function of adding or subtracting or as the case may be, because giving to the variable "op" the value of ( ,-,,/) is not possible, you have to assign a function or a method to do it, check c# documentation for more information about it.

CodePudding user response:

What you need is delegates. Delegates are basically references to a function. Here is how they look like:

Func<int, int, int> sum = (x, y) => x   y;

You can have one delegate for every operation you need.

CodePudding user response:

continuing others comments, you can even put them in a Dictionary, so that you can look them up and execute based on what the user enters

        var ops = new Dictionary<string, Func<int, int, int>>(){
            {" ", (x,y) => x y},
            {"-", (x,y) => x-y},
            {"*", (x,y) => x*y}
        };

        // user input
        var opStr = " ";
        var x = 4;
        var y = 2;

        // compute result  
        var res = ops[opStr](x, y);
 

CodePudding user response:

Delegates are certainly a quick way to solve this problem. But if you want to work towards a more complex calculator, I'd suggest building an "Abstract Syntax Tree". A graph of objects that define a maths equation, with each node representing either a value or an operator. For example;

public abstract class Ast
{
    public abstract double Calculate();
}
public class AstValue : Ast
{
    public readonly double Value;
    public AstValue(double value)
    {
        Value = value;
    }
    public override double Calculate() => Value;
    public override string ToString() => Value.ToString();
}
public class AstAdd : Ast
{
    public readonly Ast Left;
    public readonly Ast Right;
    public AstAdd(Ast left, Ast right)
    {
        Left = left;
        Right = right;
    }
    public override double Calculate() => Left.Calculate()   Right.Calculate();
    public override string ToString() => $"{Left}   {Right}";
}

var formula = new AstAdd(new AstAdd(new AstValue(1), new AstValue(2)), new AstValue(3));
var result = formula.Calculate();
  •  Tags:  
  • c#
  • Related