Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store an operator in a variable

Is there a way to store an operator inside a variable? I want to do something like this (pseudo code):

void MyLoop(int start, int finish, operator op)
{
    for(var i = start; i < finish; op)
    {
        //do stuff with i
    }
}

I could then call this method like so:

MyLoop(15, 45, ++);
MyLoop(60, 10, --);

Does something like this exist in C#?

like image 862
JMK Avatar asked Jan 10 '13 10:01

JMK


People also ask

Can we store operator in variable?

You cannot store an operator in JavaScript like you have requested. You can store a function to a variable and use that instead.

Can we store operator in a variable in Python?

Assignment operators are used in Python to assign values to variables. a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left. There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same.

Can you assign an operator to a variable?

The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables.

How do you create an operator variable in Python?

Variables & the assignment operator, `=` A variable is a way of keeping a handle on data. Variables can hold numerical or string data that we've encountered so far, as well any other type of data, as we'll see later. In order to create a variable in python, we use the assignment operator, = i.e. the equals sign.


2 Answers

I suppose something like this. You do not define the operator, but a function (lambda) which does the change for you.

void MyLoop(int start, int finish, Func<int, int> op)
{
    for(var i = start; i < finish; i = op(i))
    {
        //do stuff with i
    }
}

I could then call this method like so:

MyLoop(15, 45, x => x+1);
MyLoop(60, 10, x => x-1);
like image 140
Maarten Avatar answered Sep 21 '22 10:09

Maarten


Use a Function delegate;

Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.

void MyLoop(int start, int finish, Func<int, int> op)
{
    for(var i = start; i < finish; i = op(i))
    {
        //do stuff with i
    }
}

Then;

MyLoop(15, 45, x => ++x);
MyLoop(60, 10, x => --x);

Here is a DEMO.

like image 34
Soner Gönül Avatar answered Sep 20 '22 10:09

Soner Gönül