展平列表清单 [英] Flatten a list of lists
问题描述
例如 flatten [] = []
或 flatten [1,2,3,4] = [1,2,3,4]
或 flatten [[1,2] ,[3],4,5]] = [1,2,3,4,5]
我遇到问题可以根据扁平函数赋予什么类型来匹配类型。
以下是我的:
pre> 数据A a = B a | C [a]导出(Show,Eq,Ord)
操作符期望它的两个参数都有一个列表,我试图给它一些
flatten::(显示a,等式a,ord a)=> A a - > a
flatten(C [])=(C [])
flatten(C(x:xs))=(C flatten x)++(C flatten xs)
flatten B我)可以说这个问题是,这个 ++ A
类型的东西。我添加了 A
类型,因此该函数可以获取单个元素或元素列表。
有谁知道以不同的方式来做到这一点,或解释我可以做些什么来解决类型错误?
这个问题有点不清楚,但是列出一个列表是一个名为<$ c $的标准函数c> concat 在类型签名的前奏中 [[a]] - > [α]
。
如果您从上面开始创建嵌套列表的数据类型,则可能需要将数据类型调整为如下所示:
数据列出a = List [a] | ListOfLists [列表a]
然后你可以把它们压扁成一个列表;
flatten ::列出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]
I have to write a function that flattens a list of lists.
For example flatten [] = []
or flatten [1,2,3,4] = [1,2,3,4]
or flatten [[1,2],[3],4,5]] = [1,2,3,4,5]
I'm having trouble with the being able to match the type depending on what is given to the flatten function.
Here's what I have:
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])
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?
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
As a test,
> flatten (ListOfLists [List [1,2],List [3],ListOfLists [List [4],List[5]]])
[1,2,3,4,5]
这篇关于展平列表清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!