Operator overloading revisited
Christian Plesner Hansen
christian.plesner.hansen at gmail.com
Sun Jul 5 07:52:35 PDT 2009
> Operators are currently hardcoded in the language, but the specification
> could be recast using multimethods or double dispach and then extended to
> allow users to define operators on new "types" -- but what would be the
> nature of those types?
>
> Anything like a number (primitive, as you note the wrapping with Number is
> an old hack) does not act like a reference (object, typeof x == "object")
> type. It's a value type.
>
> This quest for extensible value types was how TC39 generalized the problem
> statement raised by decimal.
If TC39 has decided that value types are the way to go then I agree,
operators have to be considered in that context. On the other hand if
operator overloading did work for ordinary objects I would suggest
reconsidering whether value types were the simplest way to implement
use cases like decimal. I'm no fan of having numbers and booleans
hardcoded but at least it's an inconsistency that JS shares with most
other languages.
>> What does "usable" mean? If operators did work for classic objects
>> why not use them for scalars?
>
> "Usable" takes in operators for new value types, along with literal
> notation. These are aspirations, not obviously out of reach. Waldemar's
> original JS2/ES4 work from ~10 years ago had "units":
> http://www.mozilla.org/js/language/js20-2002-04/core/lexer.html#units
Custom literals is a nasty problem. To work with decimal literals,
for instance, the compiler can't be allowed to interpret numeric
constants; that has to be delegated to the decimal library. Value
types would probably make some aspects of it easier (though you have
to watch out if you want to avoid one-pass semantics) but as far as I
can see only the simple aspects.
> Since number, boolean, and string are not classic objects the generalization
> from hardcoding does not proceed from "classic objects" to novel scalar
> types, rather from the non-null/void primitive types.
That's a matter of which angle you want to view it from. But I take
the point that the same holds for my view.
>> There's === but I don't know why you
>> would want it to be anything other than object identity. Is anybody
>> relying on (typeof a == typeof b && a == b) <=> a === b?
>
> Lots of code on the web happens to depend on this because some folks (Doug
> Crockford recomments this) use === while others use == but "usually" with
> same-typed operands. I think I've even seen some code mix == and === usage.
I won't try to guess if breaking this relation will give problems in
practice. If it's really one of the central reasons for having value
types it would be worth looking into.
-- Christian
More information about the es-discuss
mailing list