Reputation: 97
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!
Upvotes: 5
Views: 5579
Reputation: 5411
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']
Upvotes: 4
Reputation: 139860
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']
Upvotes: 8