I’m trying to convert a Maybe value to a Char. I get the following error and despite my best efforts I can’t figure out how to correct this.
convertmaybe.hs:18:22:
No instance for (ToChar a)
arising from a use of `toChar'
In the expression: toChar a
In an equation for `showMaybe': showMaybe (Just a) = toChar a
Failed, modules loaded: none.
This is the code:
class ToChar a where
toChar :: a -> Char
instance ToChar Char where
toChar = id
instance ToChar Int where
toChar = head . show
showMaybe :: Maybe a -> Char
showMaybe Nothing = ' '
showMaybe (Just a) = toChar a
What am I doing wrong here?
What you are missing is the constraint in your
showMaybetype signature. Your current signaturesays that this function should work for all types
a, but it really onlyworks for types that are instances of the
ToChartype class. You can fixthis by adding the constraint to your type signature as such
A good trick to figure out type related errors is to remove the type signature and ask
GHCI what type it infers (assuming it is able to). So if you remove the signature all together
and then start up GHCI, it will give you the result