因此函数即时编写应该采用一些点(punkte)和奖励点,然后将其与punkte列表进行比较并返回相应的等级(通知列表)。
我对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)
答案 0 :(得分:2)
| p == x = noten !! (fromJust (elemIndex x p))
来自p == x
,p
和x
属于同一类型。我们将此命名为a
。
来自elemIndex x p
,p
必须是列表类型,例如[b]
。此外,x
必须是p
的潜在元素,因此必须包含b
类型。
因此,我们得到a ~ [b] ~ [a]
,这是无意义的:列表不能包含相同列表类型的元素。
此外,我们强烈建议为每个顶级定义提供预期类型。通过这种方式,GHC将产生更好的类型错误,指出我们打算定义的类型与代码产生的类型之间的差异。