将列表转换为列表列表

时间:2014-04-12 14:50:10

标签: list haskell

我有一个元组列表,元组的第一个元素可以是'a','b','c'。我想从该元组列表中创建3个列表的列表。第一个列表必须有'a'元组,第二个'b'元组和第三个'c'元组。这是代码:

group mylist = group2 mylist [[],[],[]]

group2 mylist xs = if mylist == [] then xs
            else if getFirst (head mylist) == 'a' then group2 (tail mylist) ([head mylist]++[head xs])++ (tail xs) 
            else if getFirst (head mylist) == 'b' then group2 (tail mylist) [head xs] ++ ((head mylist):[head (tail xs)]) ++ (tail xs) 
            else if getFirst (head mylist) == 'c' then group2 (tail mylist) (init xs) ++ ((head mylist):[last xs])
            else xs

我收到此错误:

Couldn't match expected type `(Char, t0, t1)'
            with actual type `[a0]'
In the expression: []
In the second argument of `group2', namely `[[], [], []]'
In the expression: group2 mylist [[], [], []] Failed, modules loaded: none.

示例输入:

[(c,1,2),(a,2,4),(c,5,6),(b,7,8),(a,9,1),(b,3,5),(c,2,5),(a,6,2),(c,1,8),(b,7,3),(a,4,4)]

输出:

[[(a,2,4),(a,9,1),(a,6,2),(a,4,4)],[(b,7,8),(b,3,5),(b,7,3)],[(c,1,2),(c,5,6),(c,2,5),(c,1,8)]]

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

如果您使用模式匹配,您会发现这更容易:

group :: [(Char, a, b)] -> [[(Char, a, b)]]
group = group' [[],[],[]]

group' :: [[(Char, a, b)]] -> [(Char, a, b)] -> [[(Char, a, b)]]
group' l [] = l
group' [as, bs, cs] (t@('a', _, _):ts) = group' [t:as, bs, cs] ts
group' [as, bs, cs] (t@('b', _, _):ts) = group' [as, t:bs, cs] ts
group' [as, bs, cs] (t@('c', _, _):ts) = group' [as, bs, t:cs] ts
group' l (_:ts) = group' l ts