2011-12-28 18 views
8

在翻译工作时,它往往是方便的功能结合到一个名称,例如:什么时候可以将函数绑定到另一个名称?

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

这个别名的名称f的功能(+1)。简单。

但是,这并不总是奏效。我找到一个导致错误的例子,试图从Data.List模块中别名nub。例如,

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, ....] 

但是,如果我明确规定的说法x那么它而不会出现错误:

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

任何人都可以解释这种现象?

+7

看看[这个问题及其答案](http://stackoverflow.com/questions/4575040/what-is-xnomonomorphismrestriction)。 – gspr 2011-12-28 12:31:35

+0

谢谢。如果您发布该答案(可能稍微扩展),那么我会接受它。 – 2011-12-28 13:28:19

+1

Nah,信贷到期的信用(即我所链接的答案)。 :-) – gspr 2011-12-28 13:30:03

回答

3

当前Ghci版本的类型默认规则有些难以理解。

您可以提供f的型号签名。或者按照克里斯先前的建议,将:set -XNoMonomorphismRestriction添加到您的~/.ghci文件中。

相关问题