问题描述
我必须编写一个函数来展平列表列表.
I have to write a function that flattens a list of lists.
例如 flatten [] = []
或 flatten [1,2,3,4] = [1,2,3,4]
或 展平 [[1,2],[3],4,5]] = [1,2,3,4,5]
我无法根据提供给 flatten 函数的内容来匹配类型.
I'm having trouble with the being able to match the type depending on what is given to the flatten function.
这是我所拥有的:
data A a = B a | C [a] deriving (Show, Eq, Ord)
flatten::(Show a, Eq a, Ord a)=>A a -> A a
flatten (C []) = (C [])
flatten (C (x:xs) ) = (C flatten x) ++ (C flatten xs)
flatten (B a) = (C [a])
据我所知,这个问题是 ++
操作符期待它的两个参数的列表,我试图给它一些 A
.我添加了 A
类型,因此该函数可以获取单个元素或元素列表.
From what I can tell the issue is that the ++
operator is expecting a list for both of its arguments and I'm trying to give it something of type A
. I've added the A
type so the function can either get a single element or a list of elements.
有谁知道以不同的方式执行此操作的不同方法,或解释我可以做些什么来修复类型错误?
Does anyone know a different way to do this differently, or explain what I can do to fix the type error?
推荐答案
有点不清楚你在问什么,但是展平一个列表是一个标准函数,叫做 concat
in prelude with类型签名 [[a]] ->[a]
.
It's a bit unclear what you are asking for, but flattening a list of list is a standard function called concat
in the prelude with type signature [[a]] -> [a]
.
如果您像上面开始的那样创建嵌套列表的数据类型,也许您想将数据类型调整为如下所示:
If you make a data type of nested lists as you have started above, maybe you want to adjust your data type to something like this:
data Lists a = List [a] | ListOfLists [Lists a]
然后你可以将这些扁平化为一个列表;
Then you can flatten these to a list;
flatten :: Lists a -> [a]
flatten (List xs) = xs
flatten (ListOfLists xss) = concatMap flatten xss
作为测试,
> flatten (ListOfLists [List [1,2],List [3],ListOfLists [List [4],List[5]]])
[1,2,3,4,5]
这篇关于展平列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!