Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

merge list

How to merge lists in Haskell

Talha Ashar

What are lists?

In Haskell, lists are a data structure that store multiple items of the same type.

[1,2,3] -- A list of integers
['a', 'b', 'c'] -- a list of characters

How to merge lists in Haskell

We can merge two lists through the ++ operator. The code below demonstrates the process:

merge :: [a] -> [a] -> [a]
merge = \s1 -> \s2 ->
  case s1 of
    [] -> s2 -- If list1 is nil, return list2
    _ -> -- otherwise
      case s2 of
        [] -> s1 -- if list2 is nil, return list1 
        _ -> s1 ++ s2 -- otherwise merge lists using (++) operator

-- call function to merge lists
main = print(merge [1,2,3] [4,5,6])


In the code above:

  • In line 1, we declare a function called merge that accepts two lists as arguments and also returns a list. The placeholder a indicates that the lists may be of any data type, but the data types of both lists must be the same.
  • In line 2, merge takes two lists called s1 and s2 as parameters.
  • In line 3, we use a case-of statement to check if s1 is an empty list. If s1 is empty, then merge returns s2 in line 4.
  • If s1 is not empty, then the function checks if s2 is empty in line 7. If s2 is empty, then the function returns s1.
  • If both lists are not empty, then the ++ operator is used to merge them in line 8.
  • In line 11, we call the merge function and print the returned list.


merge list

View all Courses

Keep Exploring