gpt4 book ai didi

haskell - Haskell非类型变量参数错误

转载 作者:行者123 更新时间:2023-12-02 10:51:19 25 4
gpt4 key购买 nike

因此,我应该在函数编写中获取一定数量的点(朋克)和奖励点,然后将其压缩到朋克列表中并返回相应的等级(注意列表)。

我对Haskell相当陌生,并且善于解释错误。

我经常会收到无限类型错误,但我从来不真正知道为什么。
你能给我解释一下吗?
也许可以给出解决方案?

功能:

import Data.Char -- i know i don't need this so far
import Data.List
import Data.Maybe

punkte = [50,54..86]
noten = [4.0,3.7,3.3,3.0,2.7,2.3,2.0,1.7,1.3,1.0]

berechneNote p bp
| bp > 20 = error "too many bonuspoints"
| bp < 0 = error "you can't give negative points"
| p > 100 = error "too many points"
| p < 0 = error "you can't give negative points"
| otherwise = berechneNote2 (p+bp) punkte

-- this constructes an infinite type aparently ?
berechneNote2 p (x:xs)
| p == x = noten !! (fromJust (elemIndex x p))
| p > x = berechneNote2 p xs
| p < x = noten !! (fromJust (elemIndex x p))

这是我得到的错误
blatt1.hs:17:48: error:
• Occurs check: cannot construct the infinite type: a ~ [a]
• In the second argument of ‘elemIndex’, namely ‘p’
In the first argument of ‘fromJust’, namely ‘(elemIndex x p)’
In the second argument of ‘(!!)’, namely
‘(fromJust (elemIndex x p))’
• Relevant bindings include
xs :: [a] (bound at blatt1.hs:16:20)
x :: a (bound at blatt1.hs:16:18)
p :: a (bound at blatt1.hs:16:15)
berechneNote2 :: a -> [a] -> Double (bound at blatt1.hs:16:1)

最佳答案

| p == x = noten !! (fromJust (elemIndex x p))

p == x中, px是同一类型。让我们将其命名为 a

elemIndex x p中, p必须为列表类型,例如 [b]。而且 x必须是 p的潜在元素,因此它必须具有 b类型。

因此,我们得到 a ~ [b] ~ [a],这是胡说八道:列表不能包含相同列表类型的元素。

另外,我们强烈建议为每个顶级定义提供预期的类型。这样,GHC会产生更好的类型错误,指出我们打算定义的类型与代码产生的类型之间的差异。

关于haskell - Haskell非类型变量参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45375994/

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