Using a Variable as an Operator

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;
}

How can I use a variable as an operator?

Basically, you can't use a variable as an operator in PHP.

All that the $v .$z. $a1[0] expression does is concatenate the variables together into a string.

I think the closest you'd be able to get to being able to use a "dynamic operator" would be to define an array of operations that you could select from using your variable.

$ops = [
'>' => function($a, $b) { return $a > $b; },
'<' => function($a, $b) { return $a < $b; },
'=' => function($a, $b) { return $a == $b; }
];

$z = '>';

$v = 50;

$a1[0] = 60;

if ($ops[$z]($v, $a1[0])) {
echo "<td>" . "test" . "</td>";
}

(Keep in mind that with your example values, $v is not greater than $a1[0], so this example won't echo anything.)


Regarding eval, since it was mentioned a couple of times in the comments on your question, most people advise against using it, for good reasons. There is almost always a better way to solve your problem.

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.

How to make an operator variable?

Use len() to count the number of characters in n:

while True:
current_number = int(input("Enter the number that you wish to be displayed: "))
print(f"The current displayed number is: {current_number}")
n = input()
if set(n) == {"+"}:
print(current_number + len(n))
elif set(n) == {"-"}:
print(current_number - len(n))
Enter the number that you wish to be displayed: 37
The current displayed number is: 37
+++++
42

Note that with this approach there's no need to arbitrarily limit the number of characters, although you can still do that explicitly by rejecting inputs where len(n) > 5.

Your original version of the check for if the string contains all "+" or "-" doesn't work:

if n == "+" or "++" or "+++" or "++++" or "+++++":

because (n == "+") or ("++") will simply return "++" (which is true) if n == "+" is not True. A "correct" way to write this check would be:

if n in ("+", "++", "+++", "++++", "+++++"):

or more simply (since these specific strings are all substrings of "+++++":

if n in "+++++":

My version of the code does this instead:

if set(n) == {"+"}:

which works by converting n to a set (reducing it to only the unique characters) -- if n contains all "+"s, then its set is {"+"}. This works for any length of n.

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.

Using a variable as arithmetic operator in Lua

You cannot substitute a native Lua operator with a variable that references a function, the only way to go about what you are attempted to do is to create a set of functions within an associative array and set the index as a reference to the respective operation you want to conduct.

Looking at your list, you have a greater than (>) and equal to (=). We create a table for these operations that takes two parameters as follows.

local operators = {
[">"] = function(x, y) return x > y end,
["="] = function(x, y) return x == y end,
-- Add more operations as required.
}

You can then invoke the respective function from the decode_prog function by obtaining the operation character from the string, along with the numeric value itself - this is possible because you can obtain the function from the associative array where the index is the string of the operation we want to conduct.

local result = operators[op](var2, number)

This calls upon the operators array, uses the op to determine which index we need to go to for our appropriate operation, and returns the value.

Final Code:

str = { '>60', '>60', '>-60', '=0' }
del = 75

local operators = {
[">"] = function(x, y) return x > y end,
["="] = function(x, y) return x == y end,
}

function decode_prog(var1, var2)
local op = string.sub(var1, 1, 1) -- Fetch the arithmetic operator we intend to use.
local number = tonumber(string.sub(var1, 2)) -- Strip the operator from the number string and convert the result to a numeric value.

local result = operators[op](var2, number) -- Invoke the respective function from the operators table based on what character we see at position one.

if result then
print("condition met")
else
print('condition not meet')
end
end

for i = 1, #str do
decode_prog(str[i], del)
end

Store an operator in a variable

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);


Related Topics



Leave a reply



Submit