This is because GHCi doesn't know how to show the data type. You can fix this by adding a deriving Show
:
data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun deriving Show
Question
I have an enum and a function to call next element of the enum.
data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun
next :: Day -> Day
next Mon = Tue
next Tue = Wed
next Wed = Thu
next Thu = Fri
next Fri = Sat
next Sat = Sun
next Sun = Mon
I try to use this by calling:
> next Mon
but the compiler shows an error:
<interactive>:35:1:
No instance for (Show Day) arising from a use of `print'
Possible fix: add an instance declaration for (Show Day)
In a stmt of an interactive GHCi command: print it
What I am doing wrong?
La solution 2
This is because GHCi doesn't know how to show the data type. You can fix this by adding a deriving Show
:
data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun deriving Show
Autres conseils
In addition to implementing Show
, if you implement Enum
you can simplify your next
function by using succ
:
data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun deriving (Show, Enum)
next :: Day -> Day
next Sun = Mon
next d = succ d
you can make a more general version of next
with this wrap-around behaviour using Bounded
:
next :: (Eq a, Enum a, Bounded a) => a -> a
next e | e == maxBound = minBound
| otherwise = succ e
data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun deriving (Eq, Show, Enum, Bounded)
The problem is when you try it in ghci
, it wants to show the result in String
. But it doesn't know how to convert that to String
.
This can be fixed by:
data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun deriving (Show)
Or in case you want to manually make up the String
:
instance Show Day where
show Mon = "Monday"
show Tue = "Tuesday"
show Wed = "Wednesday"
-- and so on