Illegal type error when using Integer as argument

Beginner trying to do the 99 problems. Here is my attempt to solve the third problem (yes):

elementAt :: [a] -> Int -> Maybe a
elementAt _ x | x <= 0 = Nothing
elementAt [] x | x > 0 = Nothing
elementAt (x: _) 1 = Just x
elementAt (_: xs) x | x > 1 = elementAt xs (x-1)

testElementAt :: IO ()
testElementAt = do
    print (elementAt []::[Int] 5)
    print (elementAt []::[Int] 0)
    print (elementAt [1, 2, 3] 2)
    print (elementAt [1, 2, 3] 5)
    print (elementAt [1, 2, 3] 1)
    print (elementAt [1, 2, 3] 0)

main :: IO ()
main = do
    testElementAt

Error message:

error:
    Illegal type: ‘5’ Perhaps you intended to use DataKinds
        print (elementAt []::[Int] 5)
                                   ^

I guess it has something to do with 5 being able to be Int as well as Float? (Just like [] which I have to type it with ::[Int] to pass the compiler?) However, the same trick does not seem to work.

What should I do?


Solution 1:

5 is here part of the type signature. If you want to specify the type of the list, you do that with:

print (elementAt ([] :: [Int]) 5)

here we thus give a type hint that the empty list is a list of Ints. The 5 in this case is thus seen as the second parameter.