在Haskell中合并两个排序列表

时间:2011-12-02 22:22:32

标签: list haskell merge

我正在尝试在Haskell中合并两个排序列表。这两个列表必须包含相同的类型,但该函数需要采用不同类型的列表。

这就是我所拥有的(我知道我需要一些代码来避免尝试从空列表中取出元素):

merge :: Ord a => [a] -> [a] -> [a]
merge [] [] = []
merge (h:first) (c:second)  | h <= c = h:merge first (c:second)
                | h > c = c:merge (h:first) second

main = merge ['a','b','c'] ['d','e','f']

问题是我是Haskell的新手,我得到了这个错误消息,我有点理解,但不知道该怎么办:

Couldn't match expected type `IO t0' with actual type `[Char]'
In the expression: main
When checking the type of the function `main'

有谁知道这意味着什么?非常感谢帮助!

2 个答案:

答案 0 :(得分:8)

main需要IO行动。如果要打印列表,请执行以下操作:

main = print $ merge ['a','b','c'] ['d','e','f']

答案 1 :(得分:4)

请注意,由于“函数合并中的非穷举模式”(即不考虑长度“1”的列表),您的程序不会运行。此外,您可以使用“@”使其更具可读性。

我将其重写为:

merge :: Ord a => [a] -> [a] -> [a]
merge xs [] = xs
merge [] xs = xs
merge a@(h:first) b@(c:second)
        | h <= c = h:merge first b
        | h > c = c:merge a second

main = print $ merge ['a','b','d'] ['c','e','f']