Programming Languages – Why Do Few Languages Have a Variable-Type Operator?

operatorsprogramming-languagesvariables

I mean it in this way:

<?php
    $number1 = 5;   // (Type 'Int')
    $operator1 = +; // (Type non-existent 'Operator')
    $number2 = 5;   // (Type 'Int')
    $operator2 = *; // (Type non-existent 'Operator')
    $number3 = 8;   // (Type 'Int')

    $test = $number1 $operator1 $number2 $operator2 $number3; //5 + 5 * 8.

    var_dump($test);
?>

But also in this way:

<?php
    $number1 = 5;
    $number3 = 9;
    $operator1 = <;

    if ($number1 $operator1 $number3) { //5 < 9 (true)
        echo 'true';
    }
?>

It doesn't seem like any languages have this – is there a good reason why they do not?

Best Answer

Operators are just functions under funny names, with some special syntax around.

In many languages, as varied as C++ and Python, you can redefine operators by overriding special methods of your class. Then standard operators (e.g. +) work according to the logic you supply (e.g. concatenating strings or adding matrices or whatever).

Since such operator-defining functions are just methods, you can pass them around as you would a function:

# python
action = int.__add__
result = action(3, 5)
assert result == 8

Other languages allows you to directly define new operators as functions, and use them in infix form.

-- haskell
plus a b = a + b  -- a normal function
3 `plus` 5 == 8 -- True

(+++) a b = a + b  -- a funny name made of non-letters
3 +++ 5 == 8 -- True

let action = (+)
1 `action` 3 == 4 -- True

Unfortunately, I'm not sure if PHP supports anything like that, and if supporting it would be a good thing. Use a plain function, it's more readable than $foo $operator $bar.