Creating an instance of the Show Typeclass for a datatype

Hello, As part of my exercise, I have to create an instance of the show typeclass for a given data type defined as: 1. *type *stat *= (*String*, Int)* *If* it was a data type, like: 1. data TrafficLight = Red | Yellow | Green It would be as simple as doing: 1. instance Show TrafficLight where 2. show Red = "Red light" 3. show Yellow = "Yellow light" 4. show Green = "Green light" However, I do not know how to declare the instance for a type, and then how to access its elements (String and Int). This is what I have so far, which does not work: 1. instance Show Stat where 2. show stat(a,b) = a instance Show Stat where show stat(a b) = b (imagine, for example, I desire to write" the value of "String" is "Int"). Thanks,

On Thu, Dec 03, 2015 at 10:16:07PM +0000, Murilo Winter wrote:
As part of my exercise, I have to create an instance of the show typeclass for a given data type defined as:
1. *type *stat *= (*String*, Int)*
That's not a new datatype, that's a type synonym.
*If* it was a data type, like:
1. data TrafficLight = Red | Yellow | Green
It would be as simple as doing:
1. instance Show TrafficLight where 2. show Red = "Red light" 3. show Yellow = "Yellow light" 4. show Green = "Green light"
However, I do not know how to declare the instance for a type, and then how to access its elements (String and Int).
This is what I have so far, which does not work:
1. instance Show Stat where 2. show stat(a,b) = a
instance Show Stat where show stat(a b) = b
You probably want something like data Stat = Stat String Int instance Show Stat where show (Stat s _) = s By why not just use data Stat = Stat String Int deriving Show instead? Tom

Hi,
instance Show Stat where
show (a, b) = "the value of " ++ a ++ " is " ++ show b
I pretty sure you need also enable TypeSynonymInstances extension. One way
to do it is to add "{-# LANGUAGE TypeSynonymInstances #-}" just at the
beginning of your module.
Best wishes
2015-12-04 1:16 GMT+03:00 Murilo Winter
Hello,
As part of my exercise, I have to create an instance of the show typeclass for a given data type defined as:
1. *type *stat *= (*String*, Int)*
*If* it was a data type, like:
1. data TrafficLight = Red | Yellow | Green
It would be as simple as doing:
1. instance Show TrafficLight where 2. show Red = "Red light" 3. show Yellow = "Yellow light" 4. show Green = "Green light"
However, I do not know how to declare the instance for a type, and then how to access its elements (String and Int).
This is what I have so far, which does not work:
1. instance Show Stat where 2. show stat(a,b) = a
instance Show Stat where show stat(a b) = b
(imagine, for example, I desire to write" the value of "String" is "Int").
Thanks,
_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
participants (3)
-
Murilo Winter
-
NCrashed .
-
Tom Ellis