Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell中显示列表时出现问题_Haskell_Syntax - Fatal编程技术网

Haskell中显示列表时出现问题

Haskell中显示列表时出现问题,haskell,syntax,Haskell,Syntax,嗨,我自己在Haskell中实现列表作为家庭作业,但我对Show有一个问题 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 ++ &

嗨,我自己在Haskell中实现列表作为家庭作业,但我对Show有一个问题

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的,所以我不知道这一点