I was trying to answer another question about polymorphism vs sharing when I stumbled upon this strange behaviour.
In GHCi, when I explicitly define a polymorphic constant, it does not get any sharing, which is understandable:
> let fib :: Num a => [a]; fib = 1 : 1 : zipWith (+) fib (tail fib)
> fib !! 30
1346269
(5.63 secs, 604992600 bytes)
On the other hand, if I try to achieve the same by omitting the type signature and disabling the monomorphism restriction, my constant suddenly gets shared!
> :set -XNoMonomorphismRestriction
> let fib = 1 : 1 : zipWith (+) fib (tail fib)
> :t fib
fib :: Num a => [a]
> fib !! 50
20365011074
(0.00 secs, 2110136 bytes)
Why?!
Ugh… When compiled with optimisations, it is fast even with monomorphism restriction disabled.
By giving explicit type signature, you prevent GHC from making certain assumptions about your code. I’ll show an example (taken from this question):
According to GHCi, the type of this function is
Eq a => [a] -> Bool, as you’d expect. However, if you declarefoowith this signature, you’ll get “ambiguous type variable” error.The reason why this function works only without a type signature is because of how typechecking works in GHC. When you omit a type signature,
foois assumed to have monotype[a] -> Boolfor some fixed typea. Once you finish typing the binding group, you generalize the types. That’s where you get theforall a. ....On the other hand, when you declare a polymorphic type signature, you explicitly state that
foois polymorphic (and thus the type of[]doesn’t have to match the type of first argument) and boom, you get ambiguous type variable.Now, knowing this, let’s compare the core:
And for the second one:
With explicit type signature, as with
fooabove, GHC has to treatfibas potentially polymorphically recursive value. We could pass some differentNumdictionary tofibinzipWith (+) fib ...and at this point we would have to throw most of the list away, since differentNummeans different(+). Of course, once you compile with optimizations, GHC notices thatNumdictionary never changes during “recursive calls” and optimizes it away.In the core above, you can see that GHC indeed gives
fibaNumdictionary (named$dNum) again and again.Because
fibwithout type signature was assumed to be monomorphic before the generalization of entire binding group was finished, thefibsubparts were given exactly the same type as the wholefib. Thanks to this,fiblooks like:And because the type stays fixed, you can use just the one dictionary given at start.