2017-07-28 125 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