串联自定义列表包装器数据类型

Mic*_*ael 2 haskell

我有以下数据类型。

data NestedList a = Elem a | List [NestedList a]
Run Code Online (Sandbox Code Playgroud)

不幸的是,创建这种数据类型的样本非常麻烦。

List [Elem 5, Elem 6, Elem 7, List [Elem 8, Elem 9, Elem 10]]
Run Code Online (Sandbox Code Playgroud)

我想创建一个fromList将使用任何类型的平面数组的辅助程序,并返回一个NestedList,该NestedList也是平面的但包含相同的数据。因此,我可以通过以下方式使用帮助程序制作上面的示例(不包括开始嵌套的部分):

fromList [5, 6, 7] == List [Elem 5, Elem 6, Elem 7]
Run Code Online (Sandbox Code Playgroud)

到目前为止,这就是我所拥有的。

fromList :: [a] -> NestedList a
fromList [] = List[]
fromList [a] = Elem a
fromList (x:xs) = List [Elem x] ++ List [fromList xs]
Run Code Online (Sandbox Code Playgroud)

错误消息是:

• Couldn't match expected type ‘[a0]’ with actual type ‘NestedList a’
• In the first argument of ‘(++)’, namely ‘List [Elem x]’


• Couldn't match expected type ‘NestedList a’ with actual type ‘[a0]’
• In the expression: List [Elem x] ++ List [fromList xs]
Run Code Online (Sandbox Code Playgroud)

我不确定为什么它告诉我我没有返回NestedList。我猜Haskell不知道该如何自然地结合我的新类型NestedList?任何帮助表示赞赏!

Zhu*_*uan 6

++仅为[a]定义。您可以:

fromList :: [a] -> NestedList a
fromList [a] = Elem a
fromList x = List $ fmap Elem x
Run Code Online (Sandbox Code Playgroud)

虽然我不知道为什么您只希望为一个元素列表提供特殊情况。