I just finished learnyouahaskell the other day, and I was trying to make sense of the Monomorphism Restriction, as described by the Haskell Wiki. I think I understand how the MR can prevent repeated evaluations, but I'm failing to see why those repeated evaluations can't be avoided by far more straightforward means.
The specific example I have in mind is the one used by the wiki:
f xs = (len,len)
where
len = genericLength xs
where genericLength
is of type Num a => [b] -> a
.
Obviously, genericLength xs
only needs to be computed once to evaluate (len,len)
, since it's the same function with the same arguments. And we don't need to see any invocations of f
to know that. So why can't Haskell do this optimization without introducing a rule like the MR?
The discussion on that wiki page tells me it has something to do with the fact that Num
is a typeclass rather than a concrete type, but even so, shouldn't it be obvious at compile-time that a pure function would return the same value--and thus the same concrete type of Num--when given the same arguments twice?