我有很长的数据类型,上面有很多记录。使用deriving(Show)时的默认show实现不再适合,因为它在几行上传播(并且变得不是人类可重定向的)。这就是为什么我想为我的数据类型实例显示每个记录字段输出一行的东西
请考虑以下代码片段,其中show Dog就是我想要的:
data Cat = Cat { catname :: String , catcolor :: String } deriving (Eq, Show)
cat1 = Cat "Garfield" "orange"
cats = [ cat1 , Cat "Tom" "grey"]
data Dog = Dog { dogname :: String , dogcolor :: String } deriving (Eq)
instance Show ( Dog ) where
show (Dog named colord)= "Dog {\n dogname = "++named++" \n dogcolor = " ++ colord ++ "\n }\n"
dog1 = Dog "comet" "white"
dog2 = Dog "Odie" "yellow"
dogs = [dog1, dog2 ]
main = do { print cat1;
print cats;
print dog1;
print dogs
}
运行时,它提供以下内容:
*Main> main
Cat {catname = "Garfield", catcolor = "orange"}
[Cat {catname = "Garfield", catcolor = "orange"},Cat {catname = "Tom", catcolor = "grey"}]
Dog {
dogname = comet
dogcolor = white
}
[Dog {
dogname = comet
dogcolor = white
}
,Dog {
dogname = Odie
dogcolor = yellow
}
]
*Main>
如何以通用方式实现此结果,即不特定于数据类型Dog? (例如在Java中,它将是内省) 我有许多具有许多记录字段的数据类型,因此每个数据执行一次实现不是一个选项
答案 0 :(得分:2)
我不知道评论中提到的包pretty-simple
。
为了获得漂亮的印刷品,我使用了包pretty-show
(我不能没有这个包BTW)。
import Text.Show.Pretty
data Cat = Cat { catname :: String , catcolor :: String }
deriving (Eq, Show)
data Dog = Dog { dogname :: String , dogcolor :: String }
deriving (Eq, Show)
cat1 = Cat "Garfield" "orange"
cats = [cat1 , Cat "Tom" "grey"]
dog1 = Dog "comet" "white"
dog2 = Dog "Odie" "yellow"
dogs = [dog1, dog2 ]
main :: IO ()
main = do
pPrint cat1
pPrint cats
pPrint dog1
pPrint dogs
这给出了:
Cat { catname = "Garfield" , catcolor = "orange" }
[ Cat { catname = "Garfield" , catcolor = "orange" }
, Cat { catname = "Tom" , catcolor = "grey" }
]
Dog { dogname = "comet" , dogcolor = "white" }
[ Dog { dogname = "comet" , dogcolor = "white" }
, Dog { dogname = "Odie" , dogcolor = "yellow" }
]
pretty-show
中的另一个有用功能是ppShow :: Show a => a -> String
,它将通用值转换为漂亮的String(如果可能)。然后pPrint
函数只是
pPrint = putStrLn . ppShow