问题描述
我得到一个数据类型Cake
I got a data type "Cake"
*data Cake = EmptyBox | Food { name :: String
, flavors :: [Cake]} deriving( Read, Eq)*
instance Show Cake where
show cake = prints cake where
prints (Food name []) = name ++ "\n"
我想打印这样的蛋糕(每个蛋糕有不同的口味)
I want to print cakes like this (each cake got different flavors)
Cake1
Chocolate
Nutella
Strawberry
Cake2
Chocolate
Vanilla
Cake3
但是我得到错误,不起作用!
But I got error, doesn't works! How can I do it?
推荐答案
对于测试数据,我使用了:
For test data, I used:
cake1 = Food{name="Cake1"
,flavors=[Food{name="Chocolate"
,flavors=[]}
,Food{name="Nutella"
,flavors=[Food{name="Strawberry"
,flavors=[]}]}]}
cake2 = Food{name="Cake2"
,flavors=[Food{name="Chocolate"
,flavors=[]}
,Food{name="Vanilla"
,flavors=[]}]}
cake3 = Food{name="Cake3"
,flavors=[]}
并将 Show Cake
写为 unlines
,该函数由类型为 Cake的函数组成>> [String]
and wrote Show Cake
as unlines
composed with a function that has type Cake -> [String]
instance Show Cake where
show = unlines . prints where
prints :: Cake -> [String]
prints EmptyBox = []
prints (Food s []) = [s] -- a Food with no subflavors
prints (Food s fs) = s:concatMap (map (" "++) . prints) fs
最后一行处理一般情况下的<$名称 s
和风味 fs
通过映射食品
c>在 fs
上打印,然后在每个子列表上映射(++)
$ b
That last line handles the general case of a Food
with name s
and flavors fs
by mapping prints
over fs
, then mapping (" "++)
over each sublist in that map, and concat'ing them together.
(" "++) :: String -> String
map (" "++) :: [String] -> [String]
map (" "++) . prints :: Cake -> [String]
map (map (" "++) . prints) :: [Cake] -> [[String]]
concat . map (map (" "++) . prints) :: [Cake] -> [String]
concatMap = concat . map
concatMap (map (" "++) . prints) :: [Cake] -> [String]
每个连续的flavor都增加了一个额外的缩进级别(这就是(++)
是for)。我们可以测试它:
Each successive level of flavors adds an extra level of indentation (that's what the (" "++)
is for). We can test it:
TestModule> putStrLn $ concatMap show [cake1, cake2, cake3]
Cake1
Chocolate
Nutella
Strawberry
Cake2
Chocolate
Vanilla
Cake3
这篇关于实例显示haskell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!