When can I bind a function to another name?

有些话、适合烂在心里 提交于 2019-12-08 16:02:39

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/8655900/when-can-i-bind-a-function-to-another-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!