Browse Source

Problem 13

completed
Craige McWhirter 7 months ago
parent
commit
922a1c25aa
Signed by: craige GPG Key ID: 7DBA9F5689EFB6AA
  1. 22
      encodeDirect.hs

22
encodeDirect.hs

@ -0,0 +1,22 @@
{-# LANGUAGE StandaloneDeriving #-}
{-# OPTIONS_GHC -Wno-orphans #-}
-- Implement the so-called run-length encoding data compression method directly.
-- I.e. don't explicitly create the sublists containing the duplicates, as in
-- problem 9, but only count them. As in problem P11, simplify the result list
-- by replacing the singleton lists (1 X) by X.
data ListItem a = Single a | Multiple Int a
deriving (Show)
encodeDirect :: (Eq a) => [a] -> [ListItem a]
encodeDirect [] = []
encodeDirect (x:xs) = encodeDirect' 1 x xs
encodeDirect' n y [] = [encodeElement n y]
encodeDirect' n y (x:xs) | y == x = encodeDirect' (n+1) y xs
| otherwise = encodeElement n y : (encodeDirect' 1 x xs)
encodeElement 1 y = Single y
encodeElement n y = Multiple n y
Loading…
Cancel
Save