Haskell & the dreaded "Ambiguous type
Every time I come back to Haskell, I'm stumped by some mysterious error messages.
Today it was the infamous "Ambiguous type variable `a0' in the constraints" for this piece of code (some tests for problem 2 of 99 Haskell problems):
module LastButOne_02_Test where
import HUnit
import LastButOne_02
lastButOne2Elements = test ["last but one for 2elems" ~: Just 1 ~=? lastButOne [1,2]]
lastButOneEmptyList = test ["last but one for empty list" ~: Nothing ~=? lastButOne [] ]
lastButOne3Elements = test ["last but one for 3elems" ~: Just 5 ~=? lastButOne [3,5,2]]
tests = TestList [
lastButOne2Elements,
lastButOne3Elements,
lastButOneEmptyList ]
main::IO()
main = (runTestTT tests) >>= (\x -> putStrLn $ show x)
The reason was the comparison between Nothing and lastButOne [], but thanks to StackOverflow and the online version of Learn You A Haskell For Great Good, I was able to figure it out.
Apparently, the compiler is not content to compare Nothing with [a], so you have to tell it which a you want:
lastButOneEmptyList = test ["last but one for empty list" ~: Nothing ~=? (lastButOne [] :: Maybe Int) ]
Et voilá, the compiler is happy, and therefore am I :-)