3 ms·
Strong typing (absence of implicit conversions) is a spectrum, with some aspects being more important than others. 1) Do you allow 1 + 1.5? Most languages say
by cousin_it 11y ago
Strong typing (absence of implicit conversions) is a spectrum, with some aspects being more important than others.
1) Do you allow 1 + 1.5? Most languages say yes, even very disciplined ones like Haskell. Very few languages say no, like Ocaml.
2) Do you allow "hello" + 1? Some languages say yes, like Java. Some languages say no, like Python. It doesn't seem very important either way.
3) Do you allow implicit conversion between pointers and integers? Most languages say no. Very few languages say yes, like C or assembly.
When people ask "is Python strongly typed?", they usually mean either "is Python statically typed?" (no, because a TV with a single color is not a color TV) or "is Python memory-safe?" (yes, unless you make a special effort to break it). Beyond these two questions, there's very little to learn from the fact that Python happens to disallow "hello" + 1.
- masklinn 11y ago> 1) Do you allow 1 + 1.5? Most languages say yes, even very disciplined ones like Haskell. That's not really because of an implicit conversion. Integral literals are typed as `Num a` and floating literals as `Fractional a`, since `+ :: Num a => a -> a -> a` both operands must be of the same type, so `1` becomes a `Fractional a :: a` and voilà, the expression is correctly typed as `Fractional a :: a`. Force `1` to a concrete integral type and you'll get a type error because there is no `Fractional Int` instance which would satisfy `(+)`: Prelude> (1 :: Int) + 1.5 <interactive>:28:14: No instance for (Fractional Int) arising from the literal `1.5' Possible fix: add an instance declaration for (Fractional Int) In the second argument of `(+)', namely `1.5' In the expression: (1 :: Int) + 1.5 In an equation for `it': it = (1 :: Int) + 1.5
- cousin_it 11y agoYeah, I know that the literal 1 has type Num a => a. Actually I suspect that's a bit of a flaw in Haskell. All the interesting things we can do with 1 as a literal (like adding it to 1.5) are also things we could do with the length of a one-element list, but in Haskell these two 1's are not interchangeable. Also, defaulting rules seem to be a wart that's necessary only because of overloaded literals. Maybe the literal 1 could have type Integer, and 1 + 1.5 could work through some other kind of typeclass magic?