在 Haskell 中显示用于打印列表的问题
Problem with Show in Haskell for printing a List
您好,我正在 Haskell 中自己实施列表作为家庭作业,但我在显示
时遇到问题
data List a = Void | Cons a (List a) -- deriving (Show, Eq)
instance (Show a) => Show (List a) where
show Void = "[]"
show (Cons a Void) = show a ++ "]"
show (Cons a b) = show a ++ ", " ++ show b
例如,如果我有
l1 = (Cons 1 (Cons 2 (Cons 3 (Cons 4 (Cons 5 Void)))))
而不是打印
[1, 2, 3, 4, 5]
它打印
1, 2, 3, 4, 5]
没有出现第一个“[”
我该如何解决这个问题?
您需要一个辅助函数,以便您可以单独处理 "["
和 "]"
字符,而不是显示列表的“内部”(元素以逗号分隔):
instance (Show a) => Show (List a) where
show l =
let showInterior Void = ""
showInterior (Cons a1 Void) = show a1
showInterior (Cons a1 b1) = show a1 ++ ", " ++ showInterior b1
in "[" ++ showInterior l ++ "]"
您好,我正在 Haskell 中自己实施列表作为家庭作业,但我在显示
时遇到问题data List a = Void | Cons a (List a) -- deriving (Show, Eq)
instance (Show a) => Show (List a) where
show Void = "[]"
show (Cons a Void) = show a ++ "]"
show (Cons a b) = show a ++ ", " ++ show b
例如,如果我有
l1 = (Cons 1 (Cons 2 (Cons 3 (Cons 4 (Cons 5 Void)))))
而不是打印
[1, 2, 3, 4, 5]
它打印
1, 2, 3, 4, 5]
没有出现第一个“[”
我该如何解决这个问题?
您需要一个辅助函数,以便您可以单独处理 "["
和 "]"
字符,而不是显示列表的“内部”(元素以逗号分隔):
instance (Show a) => Show (List a) where
show l =
let showInterior Void = ""
showInterior (Cons a1 Void) = show a1
showInterior (Cons a1 b1) = show a1 ++ ", " ++ showInterior b1
in "[" ++ showInterior l ++ "]"