Published on 28 April 2022 (Updated: 18 September 2022)

Welcome to the Merge Sort in Haskell page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

moduleMainwhereimportText.ReadimportSystem.EnvironmentimportSystem.Exit(exitWith,ExitCode(ExitFailure))importData.List(intercalate)mergeSort::Orda=>[a]->[a]mergeSortxs=head$mergeSort'$fmap(:[])xswheremergeSort'::Orda=>[[a]]->[[a]]mergeSort'[]=[]mergeSort'[x]=[x]mergeSort'(x1:x2:xs)=mergeSort'$mergex1x2:mergeSort'xsmerge::Orda=>[a]->[a]->[a]mergex[]=xmerge[]y=ymerge(x:xs)(y:ys)|x<y=x:mergexs(y:ys)|otherwise=y:merge(x:xs)ysheadMaybe::[a]->MaybeaheadMaybe[]=NothingheadMaybe(x:xs)=Justx-- Converts string in format "1, 2, 3" to a Maybe list of intstringToListMaybe::String->Maybe[Int]stringToListMaybestr=readMaybe$"["++str++"]"::Maybe[Int]-- Ensure that a list contains at least two elementsverifyListLength::Orda=>[a]->Maybe[a]verifyListLength[]=NothingverifyListLength[x]=NothingverifyListLength(x:xs)=Just(x:xs)listToString::[Int]->StringlistToString=intercalate", ".mapshowmain::IO()main=doargs<-getArgsletxs=headMaybeargs>>=stringToListMaybe>>=verifyListLengthcasexsofNothing->doputStrLn"Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""exitWith$ExitFailure1Justxs->putStrLn$listToString$mergeSortxs

Note: The solution shown above is the current solution in the Sample Programs repository as of Mar 26 2019 01:28:05. The solution was first committed on Dec 03 2018 02:16:25. As a result, documentation below may be outdated.