gpt4 book ai didi

haskell - 什么时候可以将函数绑定(bind)到另一个名称?

转载 作者:行者123 更新时间:2023-12-04 04:31:46 25 4
gpt4 key购买 nike

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

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

这将别名 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, ....]

但是,如果我明确声明参数 x然后它可以正常工作:
ghci> let f x = nub x
ghci> f [1,2,2,3,3,3]
[1,2,3]

谁能解释这种行为?

最佳答案

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

您可以为 f 提供类型签名.或添加 :set -XNoMonomorphismRestriction给您的~/.ghci按照 Chris 之前的建议提交文件。

关于haskell - 什么时候可以将函数绑定(bind)到另一个名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8655900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com