Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. data Count = One | Two | ThreeOrMore
  2. type Datum = { count :: Count, char :: Char }
  3. data Stat = Stat (Array Datum)
  4.  
  5.  
  6. instance semigroupCount :: Semigroup Count where
  7. append One One = Two
  8. append One _ = ThreeOrMore
  9. append Two _ = ThreeOrMore
  10.  
  11. toStat :: Char -> Stat
  12. toStat = Stat [{ count: One, char: _ }]
  13.  
  14. fromDatum :: Datum -> [Char]
  15. fromDatum {count, char} = case count of
  16. One -> [char]
  17. Two -> [char, char]
  18. ThreeOrMore -> []
  19.  
  20. instance semigroupStat :: Semigroup Stat where
  21. append (Stat a) (Stat b) = case Array.unsnoc a of
  22. Nothing -> Stat b -- a is empty
  23. Just { init, last } -> case Array.uncons b of
  24. Nothing -> Stat a -- b is empty
  25. Just { head, tail }
  26. | last.char == head.char ->
  27. let count = append last.count head.count
  28. in if count == ThreeOrMore
  29. then append (Stat init) (Stat tail) -- recursive call
  30. else (Stat (init <> [{ count, char: head.char }] <> tail)
  31. | otherwise -> Stat (append a b)
  32.  
  33. instance monoidStat :: Monoid Stat where
  34. mempty = Stat []
  35.  
  36. compute :: [Char] -> [Char]
  37. compute = foldMap toDatum >>> un Stat >>> foldMap fromDatum
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement