什么时候可以将函数绑定到另一个名称?
在解释器中工作时,将函数绑定到名称通常很方便,例如:
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]
任何人都可以解释这种行为吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当前 Ghci 版本中的类型默认规则有些难以理解。
您可以为
f
提供类型签名。或者按照 Chris 之前的建议,将:set -XNoMonomorphismRestriction
添加到您的~/.ghci
文件中。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.