Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some operators change their type when they are assigned?

When I ask the type of the + operator it is as you would expect

Prelude> :t (+)
(+) :: Num a => a -> a -> a

When I assign the operator to a variable then the type signatures changes

Prelude> let x = (+)
Prelude> :t x
x :: Integer -> Integer -> Integer

Why would the type of an operator change when it is assigned?

like image 456
David Howlett Avatar asked Oct 14 '25 09:10

David Howlett


1 Answers

This is the "dreaded monomorphism restriction". Essentially, when you define a

  1. new top-level name, that
  2. doesn't look like a function definition

then, by default, Haskell tries to be smart and pick a less-than-entirely general type for it. The reasons were originally to make Haskell easier to use (without it it's perhaps easier to write programs with ambiguous types), but more recently it seems to just trip everyone up since it's very unexpected behavior.

The resolution?

  1. Use GHC 7.8. After version 7.8, GHCi sessions automatically...
  2. Use -XNoMonomorphismRestriction, which turns off this behavior, or
  3. Provide a type annotation like

    let { x :: Num a => a -> a -> a; x = (+) }
    

In normal Haskell code, method (3) is most highly recommended. When using GHCi, (1) and (2) are more convenient.

like image 139
J. Abrahamson Avatar answered Oct 17 '25 00:10

J. Abrahamson