2

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?

2
  • 2
    5 is part of the type signature. Commented Jan 22, 2022 at 20:20
  • 2
    Without parentheses, elementAt []::[Int] 5 is parsed as elementAt []::([Int] 5). Commented Jan 22, 2022 at 21:37

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you. But I tried this. But without the space. Now it worked. :)) (I heard about the space-sensitivity, but not expected to be this sensitive :))
@ClémentDato: what do you mean with "without the space"?
I did it like print (elementAt ([]::[Int]) 5)
@ClémentDato: well the spaces before and after the :: are optional, so that does not matter. What matters is that you use parenthesis to make sure the type signature is applied to [], and that 5 is not seen as a type parameter.
Thank you. You are correct. I can not replicate the no-space error any more. Maybe it's just some of my unintended beginner side effect (forgetting to save before compiling).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.