Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What should I do?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading