Chr*_*lor 9 haskell monomorphism-restriction
在解释器中工作时,将函数绑定到名称通常很方便,例如:
ghci> let f = (+1)
ghci> f 1
2
Run Code Online (Sandbox Code Playgroud)
这会将名称别名f为函数(+1).简单.
但是,这并不总是有效.我发现导致错误的一个例子是尝试nub从Data.List模块中进行别名.例如,
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, ....]
Run Code Online (Sandbox Code Playgroud)
但是,如果我明确说明了参数,x那么它可以正常工作:
ghci> let f x = nub x
ghci> f [1,2,2,3,3,3]
[1,2,3]
Run Code Online (Sandbox Code Playgroud)
谁能解释这种行为?
当前 Ghci 版本中的类型默认规则有些难以理解。
您可以为 提供类型签名f。或者按照克里斯之前的建议添加:set -XNoMonomorphismRestriction到您的文件中。~/.ghci