I decided to solve the first programming from the Standford algorithm course https://class.coursera.org/algo-005 using Haskell. Despite the fact that I am very new to the language, I implemented it much faster than in C ++. I have 6+ years of experience in C ++, so it impressed me a little. But performance is disappointing: 0.19 s (C ++) versus version 9.88 (haskell). How can I improve the performance of a Haskell implementation so that it is comparable to C ++?
Here is my Haskell code
data SortedList = SortedList { inversionCount :: Int, list :: [Int] } deriving (Show) -- first list accumulator packm :: Int -> SortedList -> Int -> SortedList packm x (SortedList count xs) add = SortedList (count + add) (x:xs) merge2 :: [Int] -> [Int] -> SortedList merge2 [] xs = SortedList 0 xs merge2 xs [] = SortedList 0 xs merge2 xlist@(x:xs) ylist@(y:ys) | x < y = packm x (merge2 xs ylist) 0 | otherwise = packm y (merge2 xlist ys) $ length xlist countAndMerge :: SortedList -> SortedList -> SortedList countAndMerge (SortedList lcount lxs) (SortedList rcount rxs) = let merged = merge2 lxs rxs in SortedList (lcount + rcount + inversionCount merged) $ list merged mergesort :: [Int] -> SortedList mergesort [] = SortedList 0 [] mergesort [x] = SortedList 0 [x] mergesort xs = let leftsorted = mergesort $ take halfElements xs rightsorted = mergesort $ drop halfElements xs in countAndMerge leftsorted rightsorted where halfElements = length xs `div` 2 main = do contents <- getContents let intlist = [ read x :: Int | x <- (lines contents) ] print $ inversionCount $ mergesort intlist
, ; O (n ^ 2 * log n), O (n * log n). merge2:
merge2
| otherwise = packm y (merge2 xlist ys) $ length xlist
length xlist - O (n). , length xlist merge2, O (n ^ 2).
length xlist
otherwise = packm y (merge2 xlist ys) $ length xlist
. .
, , O (N log N). 100000 , 20 0,45 ( -O2).
, 1 RTS . mergesort - , , , .
Source: https://habr.com/ru/post/1542833/More articles:Node.js export structure structure - javascriptscrapy resolves all subdomains - pythonПоиск последней записи в коллекции метеоров - meteorThymeleaf cannot find message source - springJava 8 shortens BinaryOperator, what is it used for? - javaMediaPlayer MediaController Service - androidWhy are the Delegate and MulticastDelegate classes not considered as a base class? - inheritanceHard scrolling parallax in WebKit - javascriptLower couple implementation on vector pairs - c ++How to handle this "multiple loop" in Prolog? - prologAll Articles