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?
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.