Are Variable Operators Possible

Are Variable Operators Possible?

Not out of the box. However, it's easy to build by hand in many languages including JS.

var operators = {
'+': function(a, b) { return a + b },
'<': function(a, b) { return a < b },
// ...
};

var op = '+';
alert(operators[op](10, 20));

You can use ascii-based names like plus, to avoid going through strings if you don't need to. However, half of the questions similar to this one were asked because someone had strings representing operators and wanted functions from them.

How to store operator in variable using javascript

Avoiding the use of eval, I would recommend to use a map of functions :

var operators = {
'+': function(a, b){ return a+b},
'-': function(a, b){ return a-b}
}

Then you can use

var key = '+';
var c = operators[key](3, 5);

Note that you could also store operators[key] in a variable.

Is it possible to store an operator in a variable

One way could be to store the operators as delegates in a dictionary:

var operators = new Dictionary<string, Func<int, int, bool>>();

operators.Add("largerValue", (a, b) => a > b);
operators.Add("largerEqualValue", (a, b) => a >= b);
operators.Add("equalValue", (a, b) => a == b);

Then you can just retrieve and call the operator when you need it:

var operator = operators[compare];

for (int i = 0; i < 100000; i++)
{
if (operator(20, 50)) { }
}

How to create a variable that contains an Operator in Java?

It's not possible to assign an operator to a variable.

in 30 lines or less ... the program asks the user a simple addition, division, multiplication, or subtraction

If you want to implement it using as fewer lines as possible, build-in functional interfaces will be a good choice. For that, you need IntBinaryOperator that represents an operation done on two int arguments.

Functional interface can be implemented either by using a lambda expression or a method reference (also, you can do that with an anonymous inner class as well by it'll not be shorter). Addition operation can be represented like that:

IntBinaryOperator add = Integer::sum; // or (i1, i2) -> i1 + i2

The type of question (add, mult, etc.) should be selected randomly

For that, firstly, you need to define a Random object. In order to obtain a random integer in the given range, use nextInt() method that expects an int bound, and returns a value from 0 up to the bound (exclusive):

rand.nextInt(RANGE)

To avoid hard-coding, RANGE should be defined as a global constant.

Because your application has to interact with the user, every operation should be associated with a name that will be exposed to the user.

It can be done by declaring a record (a special kind class with final field and auto-generated constructor, getters, hashCode/equals, toString()). Syntax for declaring records is very concise:

public record Operation(String name, IntBinaryOperator operation) {}

Records representing arithmetical operations can be stored in a list. And you can pick an operation by generating a random index (from 0 up to list size).

operations.get(rand.nextInt(operations.size()))

Unlike the common getters, names of getters that will be generated by the compiler for the record will identical to names of its fields, i.e. name() and operation().

In order to use the function retrieved from the record, you need to invoke the method applyAsInt() on it, passing the two previously generated numbers.

That's how it might look like.

public class Operations {
public static final int RANGE = 100;
public static final Random rand = new Random();

public record Operation(String name, IntBinaryOperator operation) {}
public static final List<Operation> operations =
List.of(new Operation("add", Integer::sum), new Operation("sub", (i1, i2) -> i1 - i2),
new Operation("mult", (i1, i2) -> i1 * i2), new Operation("div", (i1, i2) -> i1 / i2));

public static void main(String[] args) {
// you code (instansiate a scanner, enclose the code below with a while loop)
for (int i = 0; i < 10; i++) {
Operation oper = operations.get(rand.nextInt(operations.size()));
int operand1 = rand.nextInt(RANGE);
int operand2 = rand.nextInt(RANGE);
System.out.println(operand1 + " " + oper.name() + " " + operand2); // exposing generated data to the user
int userInput = sc.nextInt(); // reading user's input
int result = oper.operation().applyAsInt(operand1,operand2); // exposing the result
System.out.println(result + "\n__________________");
}
// termination condition of the while loop
}
}

That's an example of the output the user will see:

38 add 67
105 // user input
105
_____________________
97 sub 15
...

Can you implement arithmetic operator as variables in C?

Short answer:

No, it's not possible. At least not the way you want.

Long answer:

No, you cannot. C simply does not support things like the eval function in Python. For those who does not know what it is, this will print "Hello":

s = "print('Hello')" # A string with the code we want to execute
eval(s) # Evaluate the string s as python code and execute it

If you want to do something like that in C, well just forget it. It's not possible.

You can achieve something similar with function pointers. It will look really awkward if you're not used to function pointers, but it mimics what you're talking about. Although quite badly.

int add(int a, int b) { return a+b; }
int sub(int a, int b) { return a-b; }

// Function taking two int and returning int
typedef int (operation)(int, int);

int main(void) {
operation *ops[UCHAR_MAX+1];
ops['+'] = add;
ops['-'] = sub;
printf("Sum: %d\nDiff: %d\n", ops['+'](5,3), ops['-'](5,3));
}

This prints:

Sum:  8
Diff: 2

ops is an array of function pointers. More precisely, an "array 256 of pointer to function (int, int) returning int". So we're using a single character directly to index it.

One thing to look out for here is to make sure that no negative values are passed to ops. This could happen on a machine where char is signed as default.

If you want some safety in form of error handling, you could do something like this:

int error(int a, int b) {
fprintf(stderr, "Function not implemented");
exit(EXIT_FAILURE);
}

and then do:

operation *ops[UCHAR_MAX+1];
for(int i=0; i < sizeof ops/sizeof *ops; i++)
ops[i] = error;

ops['+'] = add;
ops['-'] = sub;

This method is not worth all this extra hassle if you only want to support four operations, but it can actually come in quite handy if you're writing an emulator. I watched a very interesting youtube playlist about writing a NES emulator. It's in C++, but very oldschool so if you know C, it's not hard to follow. He talks about function pointers in part 2.

https://youtu.be/F8kx56OZQhg

Note: Not my channel. I have absolutely nothing to do with it. Was hesitating because it could look like spam, but those videos are really interesting for a coder.

Using a variable as an operator

No, that syntax isn't available. The best you could do would be an eval(), which would not be recommended, especially if the $e came from user input (ie, a form), or a switch statement with each operator as a case

switch($e)
{
case "||":
if($a>$b || $c>$d)
echo 'yes';
break;
}

(Java) Is it possible to have a function return an operator?

You can return a BiPredicate:

public BiPredicate<Integer, Integer> function(int value) {
if(value < 0) {
return (a, b) -> a >= b;
}
return (a, b) -> a <= b;
}


Related Topics



Leave a reply



Submit