majorTom
majorTom

Reputation: 67

Haskell Non type-variable argument Error

So the Function im writing is supposed to take in some amount of Points (punkte) and Bonus Points and then compair it to the punkte list and return the corresponding grade (noten list).

Im fairly new to haskell and bad at interpreting errors.

I get that Infinite type error fairly often i never really know why. Can you please explain that to me ? And maybe give a solution?

Function:

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))

and this is the Error i get

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)

Upvotes: 0

Views: 97

Answers (1)

chi
chi

Reputation: 116174

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

From p == x, p and x are of the same type. Let's name this a.

From elemIndex x p, p must be of a list type, say [b]. Also x must be a potential element of p, so it must have type b.

So, we get a ~ [b] ~ [a], which is nonsense: a list can not contain elements of the same list type.

Also, we strongly recommend to provide the intended type for every top-level definition. In that way, GHC will produce better type errors, pointing out the differences between what type we intend to define, and the type which instead results from our code.

Upvotes: 2

Related Questions