My question is related to type class instance deduction in the presence of ambiguously typed intermediary values
Prelude> :t fromInteger 0
fromInteger 0 :: Num a => a
Prelude> :t (==)
(==) :: Eq a => a -> a -> Bool
Prelude> :t (==) (fromInteger 0)
(==) (fromInteger 0) :: (Eq a, Num a) => a -> Bool
Prelude> :t (==) (fromInteger 0) (fromInteger 1)
(==) (fromInteger 0) (fromInteger 1) :: Bool
Prelude> (==) (fromInteger 0) (fromInteger 1)
False
Magic! It's unclear how or whether a
was made concrete, yet the code ran successfully!
According to the type inference rules, the type variables denoted by a
above unify successfully with each other because they have compatible Num a
constraints across the different terms. However, a
never binds to a concrete type. My question is, at runtime, which instance dictionary (or specialization, whatever) is used for the (==)
function?
Is this a case where Haskell relies on a simple binary memcmp
style comparison? Or perhaps it just picks the first instance in its list of Num
instances since in theory it shouldn't matter (as long as the algebraic properties of that instance are implemented correctly...)
Yes it is made concrete by defaulting, which is pretty much your second theory.
The expression [..] is ambiguous because the literal 4 is of Num a => a type in Haskell. 4 can be an Int, a Float or any other type that is an instance of Num, so the compiler can’t choose any particular type for the same reason above. But the Haskell Committee thought that this is too much restriction. After much debates, they compromised and added an ad-hoc rule for choosing a particular default type.
(Although it does matter which instance is chosen. For example 2^64 == 0
is True
if Int
is chosen, but False
if Integer
is chosen. Integer
is first in the default list for good reason.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With