O'Reilly logo

Haskell Cookbook by Yogesh Sajanikar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Open src/Main.hs; we will implement merge sort here.
  2. We will start with the implementation of two utility functions; group2 and merge.
  3. The group2 function is used to divide the input list in pairs. We will ensure that the pairs are sorted in the result. A single element is considered sorted:
        -- Group elements in groups of twos, but when we group it we         keep        them        -- sorted.         group2 :: Ord a => [a] -> [[a]]        group2 [] = []        -- A single element is already sorted.        group2 (x:[]) = [[x]]        -- Create groups of two and sort them        group2 (x:y:xs) = (sortPair x y) : group2 xs        where         sortPair x y | x >= y    = y : x : []                 | otherwise = x : y : []
  1. The merge function is used to merge two input lists. It is assumed that the input lists are already ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required