Search code examples
haskellmoduleinstanceshow

Haskell instance show


hi I have a haskell module which have this data type

data Blabla = Blabla [Integer]
[Char]
[(Integer,Char,Char,Integer,String)] Integer

I want to show them like that with using instance show

integers=[1,2,3]
chars=[a,b,c]
specialList=[(1,a,b,2,cd),(3,b,c,4,gh)]
interger=44

thanx for helping...


Solution

  • Assuming you just want the default style, simply adding deriving Show to the end of the line as below should do the job.

    data Blabla = Blabla [Integer] [Char] [(Integer,Char,Char,Integer,String)] Integer deriving Show
    

    Will work fine as all of the primitive types that Blabla is built from are "showable". For example

    *Main> Blabla [1,2,3] "abc" [(1,'A','B',2,"Three")] 54
    Blabla [1,2,3] "abc" [(1,'A','B',2,"Three")] 54
    

    It might be better to build Blabla as a named structure

     data BlaBlu = BlaBlu {
        theNumbers :: [Integer] ,
        theIdentifier :: [Char] ,
        theList :: [(Integer,Char,Char,Integer,String)]  ,
        theInteger :: Integer
     } deriving Show
    

    By doing this you might be able to make the structure make more sense.

    *Main> BlaBlu [1,2,3] "abc" [(1,'A','B',2,"Three")] 54
    BlaBlu {theNumbers = [1,2,3], theIdentifier = "abc", theList = [(1,'A','B',2,"Three")], theInteger = 54}
    

    Do the same thing for the list structure and hopefully the code will be more readable.

    If you want to write your own instance of Show so you can customize it then you can remove the deriving Show and just write your own instance, such as:

    instance Show Blabla where                                                                                       
        show (Blabla ints chars list num) =                                                                            
        "integers = " ++ show ints ++ "\n" ++                                                                        
        "chars = " ++ show chars ++ "\n" ++                                                                          
        "specialList = " ++ show list ++ "\n" ++                                                                     
        "integer = " ++ show num              
    

    Where the implementation produces roughly the output you asked in the original question.

    *Main> Blabla [1,2,3] "abc" [(1,'A','B',2,"Three")] 54
    integers = [1,2,3]
    chars = "abc"
    specialList = [(1,'A','B',2,"Three")]
    integer = 54