The following code doesn't compile:
import Data.Bits
xor2 = xor
However, once I added the type info, it compiles:
import Data.Bits
xor2 :: Bits a => a->a->a
xor2 = xor
I can't explain this. Any explanations?
This is a problem with the dreaded monomorphism restriction (MMR), which is enabled by default. The MMR is a rule that forces top-level bindings that do not look like functions (ie x = ...
vs x a = ...
) to have monomorphic bindings unless they have an explicit polymorphic type signature.
The problem is that Bits a => a -> a -> a
is polymorphic (note the type variable a
), and Haskell does not know how to choose a default type for a
that satisfies the Bits
constraint.
Once you add a type signature, the MMR is appeased and you can have a top-level binding that's polymorphic. Another option is to "eta-expand" the definition by adding a named argument; since xor2
now syntactically looks like a function, the MMR does not apply:
xor2 x = xor x
You can also turn the MMR off with a language extension. You can put this at the top of your module:
{-# LANGUAGE NoMonomorphismRestriction #-}
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