Advertisement
banovski

Ninety-Nine Haskell Problems: #9

Mar 31st, 2025 (edited)
573
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Haskell 1.83 KB | Source Code | 0 0
  1. -- Pack consecutive duplicates of list elements into sublists. If a
  2. -- list contains repeated elements they should be placed in separate
  3. -- sublists.
  4.  
  5. import Data.List (group)
  6. -- "group" is imported as a reference function
  7.  
  8. main :: IO ()
  9. main = do
  10.   putStrLn "Test strings: "
  11.   mapM_ print $ chunksOfFour testStringList
  12.   putStrLn "\nTested functions validity check: "
  13.   mapM_ (print . testFunction) testFuncList
  14.  
  15. testStringList :: [String]
  16. testStringList = pure (\a b c d -> [a, b, c, d])
  17.   <*> "ab"
  18.   <*> "ab"
  19.   <*> "ab"
  20.   <*> "ab"
  21.  
  22. chunksOfFour :: [a] -> [[a]]
  23. chunksOfFour [] = []
  24. chunksOfFour lst = take 4 lst : chunksOfFour (drop 4 lst)
  25.  
  26. testFuncList :: Eq a => [[a] -> [[a]]]
  27. testFuncList = [zero, one, two]
  28.  
  29. testFunction :: (String -> [String]) -> Bool
  30. testFunction function =
  31.   -- group from Data.List is used to produce reference results
  32.   map function testStringList == map group testStringList
  33.  
  34. -- Functions were tested on a list with duplicates, 1000405 items
  35. -- long. Time each function takes to complete the task is measured in
  36. -- ticks.
  37.  
  38. -- 128 ticks
  39. zero :: Eq a => [a] -> [[a]]
  40. zero = group
  41.  
  42. -- 221 ticks
  43. one :: Eq a => [a] -> [[a]]
  44. one [] = []
  45. one [a] = [[a]]
  46. one lst = go [head lst] (tail lst)
  47.   where
  48.     go a [] = [a]
  49.     go a (x:xs)
  50.         | head a == x = go (a ++ [x]) xs
  51.         | otherwise = a : go [x] xs
  52.  
  53. -- 285 ticks
  54. two lst =
  55.   let
  56.     itemsAsLists = map (:[]) lst
  57.     h = head itemsAsLists
  58.     t = tail itemsAsLists
  59.     join a [] = [a]
  60.     join acc (x:xs)
  61.       | head acc == head x = join (acc ++ x) xs
  62.       | otherwise = acc : join x xs
  63.   in
  64.     join h t
  65.  
  66. -- Test strings:
  67. -- ["aaaa","aaab","aaba","aabb"]
  68. -- ["abaa","abab","abba","abbb"]
  69. -- ["baaa","baab","baba","babb"]
  70. -- ["bbaa","bbab","bbba","bbbb"]
  71.  
  72. -- Tested functions validity check:
  73. -- True
  74. -- True
  75. -- True
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement