gpt4 book ai didi

haskell - "Type error in application": "unification would give infinite type"

转载 作者:行者123 更新时间:2023-12-03 13:18:26 25 4
gpt4 key购买 nike

我开始与 Haskell 合作,但我试图进行的这种平等检查没有成功。

我有一个函数,countLetter a [b] c , 其中 a是一个字符,b是一个字符列表和 c是一个整数。 (类型声明通过很好。)但是我遇到了这个表达式的问题:

if a == head(b)

给我以下信息:
Type error in application

*** Expression : a == head b
*** Term : a
*** Type : [a]
*** Does not match : a
*** Because : unification would give infinite type

如果需要,我的完整代码是这样的:
countLetter :: char -> [char] -> int

countLetter a [b] c = if null b

then []
else
if a == head(b)
then countLetter a tail(b) c+1
else
countLetter head(b) tail(b) c

任何帮助或建议将不胜感激。谢谢你。

最佳答案

首先,Haskell 中的类型以大写字母开头。如果您在类型签名中使用以小写字母开头的标识符,它们将被解释为类型变量。所以你的类型char -> [char] -> inta -> [a] -> b 相同,这对于您的函数来说不是一个明智的类型。您的需求Char -> [Char] -> Int .

其次[]不是 Int 类型的有效值.修复您的类型签名应该会产生一条错误消息,以不那么模棱两可的方式告诉您这一点。

它还应该告诉你 null b是类型错误,因为 bChar 类型(你的函数的第二个参数是类型 [Char] 并且你已经将它与模式匹配 [b] ,将 b 绑定(bind)到该列表中包含的单个 Char)和 null接受一个列表,而不是一个 Char,作为它的参数。

为了澄清最后一点:

函数的第二个参数是一个列表。通过写 [b]在您的参数列表中,您将该参数与模式 [b] 进行匹配.换句话说,写 countLetter a [b] c = blabla和写法一样:

countLetter a theList c =
case theList of
[b] -> blabla

所以你说:“函数的第二个参数必须是一个包含一个元素的列表,并且该元素应称为 b”。这不是你想说的。您想说的是“函数的第二个参数(顺便说一下,是一个列表)应称为 b”。为此,您只需写 countLetter a b c = blabla .

list 类型的参数不必与其他类型的参数有任何不同的表示。

关于 haskell - "Type error in application": "unification would give infinite type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13959194/

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