I am using the Haskell Stack to create a program. My program builds okay but I would like to write a test file so that I can run stack test on my existing program. My problem is that my function to test returns a Maybe type, which cannot be outputted using the syntax putStrLn f. I am attempting to write a function in my test file that takes a Maybe value and returns "Nothing" if it was given Nothing, or a string containing a if it was given Just a.
Here is my code so far:
printMaybe :: Show a => Maybe a -> String
printMaybe Nothing = "Nothing"
printMaybe (Just a) = show a
and main contains the line
putStrLn $ printMaybe (Nothing)
My error message is:
test\Spec.hs:12:16: error: * Ambiguous type variable
a0' arising from a use ofprintMaybe' prevents the constraint(Show a0)' from being solved. Probable fix: use a type annotation to specify whata0' should be. These potential instances exist: instance Show Ordering -- Defined inGHC.Show' instance Show Integer -- Defined inGHC.Show' instance Show a => Show (Maybe a) -- Defined inGHC.Show' ...plus 22 others ...plus 27 instances involving out-of-scope types (use -fprint-potential-instances to see them all) * In the second argument of($)', namely `printMaybe (Nothing)' In a stmt of a 'do' block: putStrLn $ printMaybe (Nothing) In the expression: do putStrLn ("====== Tests Start ======") putStrLn $ printMaybe (Nothing) | 12 | putStrLn $ printMaybe (Nothing) | ^^^^^^^^^^^^^^^^^^^^
Any help would be much appreciated :)
As the error says, the problem is not with your printMaybe, it is with printMaybe Nothing in your do block, since then it is unclear what the a type is.
You thus likely have something like:K
main = do
putStrLn "====== Tests Start ======"
putStrLn (printMaybe Nothing)
But it is unclear what the a of the type Maybe a is for Nothing. You can give a hint to the compiler with:
main = do
putStrLn "====== Tests Start ======"
putStrLn (printMaybe (Nothing :: Maybe Int))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With