我什么时候可以将函数绑定到另一个名字? [英] When can I bind a function to another name?

查看:123
本文介绍了我什么时候可以将函数绑定到另一个名字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在解释器中工作时,将函数绑定到名称通常很方便,例如:

  ghci>让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>让f = nub
ghci> f [1,2,2,3,3,3]

< interactive>:1:14:
(Num())
文字'3'
可能的修正:为(Num())
添加一个实例声明在表达式中:3
在'f'的第一个参数中,即`[1,2, 2,3,...]'
在表达式中:f [1,2,3,...]

然而,如果我明确地声明 x 这个参数,那么它就不会有错误:

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

任何人都可以解释这种行为吗?

解决方案

在当前Ghci版本中输入默认规则有点难以理解。



您可以为 f 提供类型签名。或者按照Chris的建议,将:set -XNoMonomorphismRestriction 添加到〜/ .ghci 文件中。


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.

这篇关于我什么时候可以将函数绑定到另一个名字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆