9

When working in the interpreter, it's often convenient to bind a function to a name, for example:

ghci> let f = (+1)
ghci> f 1
2

This aliases the name f to the function (+1). Simple.

However, this doesn't always work. One example I've found which causes an error is trying to alias nub from the Data.List module. For example,

ghci> :m Data.List
ghci> nub [1,2,2,3,3,3]
[1,2,3]
ghci> let f = nub
ghci> f [1,2,2,3,3,3]

<interactive>:1:14:
    No instance for (Num ())
      arising from the literal `3'
    Possible fix: add an instance declaration for (Num ())
    In the expression: 3
    In the first argument of `f', namely `[1, 2, 2, 3, ....]'
    In the expression: f [1, 2, 2, 3, ....]

However, if I explicitly state the argument x then it works without error:

ghci> let f x = nub x
ghci> f [1,2,2,3,3,3]
[1,2,3]

Can anyone explain this behaviour?

Chris Taylor
  • 46,912
  • 15
  • 110
  • 154
  • 7
    Check out [this question and its answer](http://stackoverflow.com/questions/4575040/what-is-xnomonomorphismrestriction). – gspr Dec 28 '11 at 12:31
  • Thanks. If you posted that as an answer (possibly a little expanded) then I'd accept it. – Chris Taylor Dec 28 '11 at 13:28
  • 1
    Nah, credit where credit's due (i.e. the answer I linked to). :-) – gspr Dec 28 '11 at 13:30
  • 1
    If gspr doesn't want to make it an answer you can accept, you can answer your own question with what you've learned and, after due time, accept it, so the question appears as resolved. – Daniel Fischer Dec 28 '11 at 13:47
  • The dreaded `MonomorphismRestriction` strikes again! We really should try to address this. Can we get it removed for, say, Haskell 2012? – Dan Burton Dec 28 '11 at 20:46
  • 1
    @DanBurton Your proposal is already well under way. [1](http://hackage.haskell.org/trac/haskell-prime/wiki/MonomorphismRestriction) [2](http://hackage.haskell.org/trac/haskell-prime/wiki/NoMonomorphismRestriction) [3](http://hackage.haskell.org/trac/haskell-prime/ticket/131) – Daniel Wagner Dec 28 '11 at 22:41
  • @DanielWagner - Milestone 2010 deleted :( when does the Haskell committee plan on making a new standard a la 2010? – Dan Burton Dec 29 '11 at 05:34

1 Answers1

3

Type defaulting rules in current Ghci versions are somewhat inscrutable.

You can supply a type signature for f. Or add :set -XNoMonomorphismRestriction to your ~/.ghci file as was advised by Chris earlier.

Mischa Arefiev
  • 5,227
  • 4
  • 26
  • 34