Skip to content

Instantly share code, notes, and snippets.

@cronokirby
Last active February 5, 2021 09:15
Show Gist options
  • Select an option

  • Save cronokirby/dfd58d1c7f345a23265846d657335957 to your computer and use it in GitHub Desktop.

Select an option

Save cronokirby/dfd58d1c7f345a23265846d657335957 to your computer and use it in GitHub Desktop.
import Data.Sequence (Seq (Empty, (:<|), (:|>)))
import qualified Data.Sequence as Seq
newtype RunLength a = RunLength (Seq.Seq (Int, a))
deriving (Eq, Show)
singleton :: a -> RunLength a
singleton a = RunLength (Seq.singleton (1, a))
runLengthToList :: RunLength a -> [a]
runLengthToList (RunLength runs) = foldMap (uncurry replicate) runs
instance Eq a => Semigroup (RunLength a) where
RunLength (as :|> (countA, a)) <> RunLength ((countB, b) :<| bs)
| a == b = RunLength ((as :|> (countA + countB, a)) <> bs)
RunLength as <> RunLength bs = RunLength (as <> bs)
instance Eq a => Monoid (RunLength a) where
mempty = RunLength Empty
runLengthFromList :: Eq a => [a] -> RunLength a
runLengthFromList = foldMap singleton
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment