Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two sorted lists in Haskell

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!

like image 902
Jen Avatar asked Dec 02 '11 22:12

Jen


2 Answers

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']
like image 122
hammar Avatar answered Sep 18 '22 20:09

hammar


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']
like image 36
lbolla Avatar answered Sep 18 '22 20:09

lbolla