Dmitry Sokolov
Dmitry Sokolov

Reputation: 383

What is programming language support define your own custom operator?

I know that many language, C++, Python etc, support operator overloading, and we can redefine standart operators like +. But if we need add new operator?

Upvotes: 0

Views: 877

Answers (2)

John Cvelth
John Cvelth

Reputation: 522

I don't think there is any language with the feature. But you can always create your own interpreter or something similar in order to process your custom code and transform it into code of the desired language. As the simplest variant, you can write a tool(or even extension for IDE), which will find something like

return_type operator$(typename arg1, typename arg2);

and insert something like

return_type reloaded_operator_dollar(typename arg1, typename arg2);

in its place. The same goes for transforming

auto result = arg1 $ arg2;

into

auto result = reloaded_operator_dollar(arg1, arg2);

upd: It seems, there are such feature in FORTH and Haskell. Thanks to Neil Butterworth for the information.

Upvotes: -1

hnefatl
hnefatl

Reputation: 6037

Neither C++ nor Python (C++, Python) support the overloading of "new" operators (although C++ does support overloading the new operator). Overloading operators is just syntactic sugar though - you can always just define a member function, name it something that explains its behaviour better than a single character operator could, and call it instead.

There do exist languages where this is possible: for example Haskell, a beautiful language that does allow you to define your own operators, by using symbols for the name and surrounding them with parentheses, eg:

(!!!) :: [a] -> Integer -> a
(x:xl) !!! 0 = x
(_:xl) !!! n = xl !!! (n-1)
    _  !!! _ = error "Index out of bounds"

(note this is just a redefinition of the standard !! function, I'm unimaginative...)

Upvotes: 2

Related Questions