Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I like Lua's solution to this dilemma:

    5 == "5" -- false
    5 + "5"  -- 10
    5 .. "5" -- 55
It's just dynamic enough, none of the conversions are surprising and they're frequently helpful.


Wow this is actually the worst solution I could imagine.


...why though?

5 and "5" are different objects, one is a number and one is a string, they shouldn't compare for equality.

+ in Lua is only addition, you can't add a string to anything, so if that string can be a number, that's obviously what was intended.

Similarly, .. is only concatenation, so if you're concatenating a number you clearly want it to be a string.

It works great in practice. How is this better than anything which languages that overload addition and concatenation can offer?


> if that string can be a number, that's obviously what was intended

Maybe that would be a reasonable assumption in a world where programmers were omniscient and never made mistakes. In practice these "do what I mean" rules just tend to make it easier for poorly-specified programs to produce nonsense without signaling that anything is wrong. If your program intends to add two numbers and one of the inputs turns out to be a string then someone gave you bad input; the right solution to that is to report an error, not continue with bad data. Perhaps it's only an accident that the string happens to look like a number this time. Maybe it wasn't intended to be a number at all, and some parameters got swapped or an input file was corrupted.

Also, that rule is too broad. The string "5" could be treated as a number, sure, but so could "five" or "⑨" or "¾". So why is "five" + "⑨¾" an error and not 14.75 (or even "14¾")? If you want to accept number-like strings as numbers, fine, but there should be an explicit process where the programmer defines exactly what form the input can take and how to perform the conversion to a number. Implicit conversions skip that step and expose the internal defaults of the language to the end user.


"Shouldn't compare" is not the same as "should compare but return false".


If you could do relative comparisons like "5" < 5 and get a boolean answer, that would be surprising. I don't see anything controversial, however, about unequivocally reporting that objects of different types are unequal. In Lua anything can be tested for (in)equality but asking whether a string is greater than or less than a number is an error, as is performing an ordered comparison involving any other type(s).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: