I am trying to merge two sorted lists in 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:
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. 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). 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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With