0

I need to be able to manipulate variables like so.

Firstly find the variable and check what it is (in this case an operator * / + etc), and then reverse it. For example, the value of ~(5+9) is -14 and the value of ~(3-5) is 2.

How do I go about doing so?

Ryan
  • 1
  • 2
  • Do you mean "negate", rather than "reverse"? This is easily accomplished with a negative sign rather than a tilde, and works for both of your examples. Since operators are not variables, what do you mean by "find the variable and check what it is"? Are you wanting to know how to automate this? – Matt Jordan Feb 29 '16 at 21:59

3 Answers3

0
1> F=fun({A,'+',B}) -> B+A; ({A,'-',B}) -> B-A; ({A,'/',B}) -> B/A end.
#Fun<erl_eval.6.54118792>
2> F({5,'+',9}).
14
3> F({3,'-',5}).
2
Greg
  • 8,230
  • 5
  • 38
  • 53
0

What do you mean by reversing the operator? It sounds like you would want to do the opposite - so addition becomes subtraction and vice versa, and multiplication becomes division and vice versa. But your examples indicate that you want to perform the operation and then negate the answer. For instance, if you were to just "reverse the operator," then 5+9 would become 5-9=-4. Again, for you to get 5+9=-14 you would have to negate the answer of the operation 5+9. Can you clarify before we proceed?

0
custom_action(A, Operator, B) ->
    operate({A, Operator, B}) * -1.

operate({A, "+", B}) -> A + B;
operate({A, "-", B}) -> A - B;
operate({A, "*", B}) -> A * B;
operate({A, "/", B}) -> A / B.

Now you can use custom_action/3 like custom_action(5, "+", 9) to get -14 and custom_action(3, "-", 5) to get 2.

Dariush Alipour
  • 318
  • 3
  • 11