1

I can't figure out how to annotate the mylast3 test properly:

import Test.HUnit

mylast :: [a] -> Maybe a
mylast [] = Nothing
mylast [x] = Just x
mylast (_:xs) = mylast xs

testsMyLast =
  [TestCase $ assertEqual "mylast1" (Just 1) $ mylast [1],
   TestCase $ assertEqual "mylast2" (Just 'b') $ mylast "ab",
   TestCase $ assertEqual "mylast3" Nothing $ mylast []  <== how to test this correctly?
   ]

main = do runTestTT $ TestList testsMyLast

I'm getting the following error pointing at the line "TestCase $ assertEqual "mylast3":

No instance for (Show a0) arising from a use of assertEqual The type variable a0 is ambiguous

recursion.ninja
  • 5,377
  • 7
  • 46
  • 78
Denis Gorodetskiy
  • 2,884
  • 3
  • 21
  • 23

1 Answers1

4

Since the list [] does not have any members, it can only be deduced from type inference that [] is of type [a].

For a list to be "showable" it must be an instance of the typeclass Show. A list is only an instance of Show if the members of the list are also instances of Show.

But the type checker can't deduce the type of [] to a more specific type than [a]. We cannot know if a is an instance of Show so we also cannot know if [a] is in turn an instance of Show.

If we simply annotate a specific type ([] :: [Int]) there will be no error!

This is because we know that Int is an instance of Show and therefore [Int] is also an instance of Show. Now the compiler can infer the necessary information to print the list!

recursion.ninja
  • 5,377
  • 7
  • 46
  • 78