Haskell instance show

时间秒杀一切 提交于 2019-12-13 06:29:13

问题


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...


回答1:


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


来源:https://stackoverflow.com/questions/5677749/haskell-instance-show

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!