2 ms·
> 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 liter
by 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?