Why aren't the inferred types of these Haskell functions all the same?
Asked Answered
B

1

7

I define five functions that seem to me like they should be equivalent (and, therefore, have the same type). But the inferred types are different. I put the following five lines in type-inference.hs:

f1 a b = a + b
f2 a = \b -> a + b
f3 = \a -> \b -> a + b
f4 a = (a+)
f5 = (+)

And then I load up Hugs:

Hugs> :load type-inference.hs
Main> :type f1
f1 :: Num a => a -> a -> a
Main> :type f2
f2 :: Num a => a -> a -> a
Main> :type f3
f3 :: Integer -> Integer -> Integer
Main> :type f4
f4 :: Num a => a -> a -> a
Main> :type f5
f5 :: Integer -> Integer -> Integer

What happened here?

Britanybritches answered 30/11, 2013 at 15:51 Comment(0)
B
8

It is the MonomorphismRestriction at work.

Prelude> let f5 = (+)
Prelude> :t f5
f5 :: Integer -> Integer -> Integer
Prelude> :set -XNoMonomorphismRestriction 
Prelude> let f5 = (+)
Prelude> :t f5
f5 :: Num a => a -> a -> a

Because of that, the type synthesizer is forced to default early on some types.

Bosk answered 30/11, 2013 at 15:55 Comment(1)
Oh. Now I know. This is the first time I have run up against (or even heard of) the monomorphism restriction. Thanks for the link!Britanybritches

© 2022 - 2024 — McMap. All rights reserved.