简体   繁体   English

在Haskell中合并两个排序列表

[英]Merge two sorted lists in Haskell

I am trying to merge two sorted lists in Haskell. 我试图在Haskell中合并两个排序列表。 The two lists must contain the same types, but the function needs to take lists with different types. 这两个列表必须包含相同的类型,但该函数需要采用不同类型的列表。

This is what I have got(I know that I need some code to avoid trying to take elements out of empty lists as well): 这就是我所拥有的(我知道我需要一些代码来避免尝试从空列表中取出元素):

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']

The thing is that I am new to Haskell and I get this error messege, that I kind of understand but don't know that to do about: 问题是我是Haskell的新手,我得到了这个错误消息,我有点理解,但不知道该怎么做:

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

Does anyone know what this means? 有谁知道这意味着什么? Help is really appreciated! 非常感谢帮助!

main needs to be an IO action. main需要是IO行动。 If you want to print the list, do something like this: 如果要打印列表,请执行以下操作:

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

Note that your program does not run, because of "Non-exhaustive patterns in function merge" (that is, lists of length "1" are not considered). 请注意,由于“函数合并中的非穷举模式”(即不考虑长度“1”的列表),您的程序不会运行。 Moreover you can use "@" to make it more readable. 此外,您可以使用“@”使其更具可读性。

I'd rewrite it as: 我把它重写为:

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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM