2017-07-28 131 views
0

因此,函数即时写作应该采取一定数量的点(punkte)和奖励点数,然后将其比较为punkte列表并返回相应的评分(记录列表)。Haskell非类型变量参数错误

对于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

为什么你在这里使用'elemIndex'? –

+0

我应该用什么来代替? – Tom507

+0

您可能需要为您的功能添加类型注释。这应该有助于你对自己的行为有一个良好的心理模型,并且如果ghc推断出与你声明的你想要的东西不一致的话,会导致更好的错误信息。 – gallais

回答

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

p == xpx是同一类型的。我们来命名这个a

elemIndex x p,p必须是列表类型,如[b]。另外x必须是p的潜在元素,因此它必须具有类型b

所以,我们得到a ~ [b] ~ [a],这是无稽之谈:一个列表不能包含相同列表类型的元素。

此外,我们强烈建议为每个顶级定义提供预期类型。通过这种方式,GHC将产生更好的类型错误,指出我们打算定义的类型与由我们的代码产生的类型之间的差异。

+0

我会坐在那里盯着下一个我们的THX快速回答! – Tom507