99-haskell-problems/Problems 11-20/problem_13.hs

22 lines
552 B
Haskell
Raw Normal View History

2024-05-24 18:50:16 -05:00
-- This is the same solution as in Problem 11
data ListItem a = Single a | Multiple Int a deriving (Show)
getListItem :: (Int, a) -> ListItem a
getListItem (1, x) = Single x
getListItem (n, x) = Multiple n x
encode :: (Eq a) => [a] -> [(Int, a)]
encode =
foldr
( \x acc -> case acc of
[] -> [(1, x)]
(hd@(hd_n, hd_a) : tl) ->
if x == hd_a
then (hd_n + 1, hd_a) : tl
else (1, x) : hd : tl
)
[]
encodeModified :: (Eq a) => [a] -> [ListItem a]
encodeModified = map getListItem <$> encode