Reputation: 97
Implement a function (myData2Fun) that takes a string as input and expands its compressed representation according to the rules for encoding series lengths. The essence of compression is that consecutive identical characters are combined into one group.For example:
1. Input: myData2Fun "C"
Output: [Single "C"]
2. Input: myData2Fun "cvvccf"
Output:[Single 'c',Multiple 'v' 2,Multiple 'c' 2,Single 'f']
It is also necessary to implement the data type required to solve the problem.
I am trying to solve the problem as follows:
data MyData2 = Multiple Char Integer | Single Char deriving(Show)
myData2Fun (h:t) = fff h t 1
fff x (h:t) acc
| h == x = fff x t (acc + 1)
| h /= x && acc > 1 = Multiple x acc : fff h t 1
| h /= x && acc == 1 = Single x : fff h t 1
fff x [] acc
| acc>0 = Multiple x acc : []
| acc == 0 = Single x : []
But my program is on a line with a single character, for example Input: myData2Fun "c" returns Output: [Multiple 'c' 1], instead of Output: [Single 'c']. Help me find the error and fix the code.
Upvotes: -1
Views: 202
Reputation: 26191
As @chepner hints you may use Data.List.group
to simplify your job while keeping your MyData2
data type
import Data.Bool (bool) -- ternary operator
import Data.List (group)
f s = map (\g@(c:_) -> let n = length g
in bool (Single c) (Multiple c n) (n > 1)) (group s)
*Main> f "cvvccf"
[Single 'c',Multiple 'v' 2,Multiple 'c' 2,Single 'f']
Upvotes: 1