[Haskell-cafe] monomorphism restriction

Ryan Ingram ryani.spam at gmail.com
Fri Jun 13 20:27:01 EDT 2008


On 6/11/08, Rex Page <page at ou.edu> wrote:
> Please remind me, again, of the advantages of f being something different
> from the formula defining it.

fibs !a !b = a : fibs b (a+b)
-- fibs :: Num a => a -> a -> [a]

n = head $ drop 1000000 $ fibs 1 1
-- n :: Integer (due to monomorphism restriction.)

sumns 0 = 0
sumns x = sumns (x-1) + n

Without the monomorphism restriction, computing n is a function call;
it is evaluated each time it is asked for.

With the monomorphism restriction, n is a CAF and it is updated in
place after it's been evaluated for the first time.

Evaluating "sumns 1000" could take 1000 times as long without the
monomorphism restriction, which definitely seems surprising as a user
until you understand whatis going on behind the scenes with dictionary
passing.

If you do not want the MR, you have these options:
1) turn off explicitly (in GHC you can use -fno-monomorphism restriction)
2) add a type signature yourself (f :: Num a => [a] -> a)
3) eta-expand (f xs = foldr (+) 0 xs)

  -- ryan


More information about the Haskell-Cafe mailing list