Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell group function / First element always missing

I want to write a function called group that takes a list of type [a] and returns a a list of list of type [[a]] containing identical characters. Here is a simple example of the expected behaviour:

group [1,1,2,1,3,3,3] ⇒+ [[1,1],[2],[1],[3,3,3]]

group "aaabbcdddd" ⇒+ ["aaa","bb","c","dddd"]

I wrote the following code but the problem is that this code always misses the first element from the original list

group [] = []
group (x:xs) = groupHelper xs x []

groupHelper :: Eq a => [a] -> a -> [[a]] -> [[a]]
groupHelper [] prev fs = fs
groupHelper (x:xs) prev [] = groupHelper xs prev [[x]]
groupHelper (x:xs) prev fs = if (x == prev) then groupHelper (xs) (x) ((init fs) ++ [(last(fs)++[x])]) 
     else groupHelper (xs) x (fs++[[x]])

The code would produce the following output for this input.

group [1,1,2,1,3,3,3] ⇒+ [[1],[2],[1],[3,3,3]]

=> Here a 1 at the beginning of the first list would be missing


group "aaabbcdddd" ⇒+ ["aa","bb","c","dddd"]

=> Here one 'a' at the beginning of the first list would be missing

I hope someone can help me to solve this bug. Thank you very much

like image 426
Jan Kreischer Avatar asked Dec 21 '25 19:12

Jan Kreischer


1 Answers

When you call groupHelper the first time (from group) you’re passing the prev arg, but the helper uses it only for comparison. Solution could be to add the fist item as the first element of the first group on first call. Like this: group (x:xs) = groupHelper xs x [[x]]

like image 117
Ádám Révész Avatar answered Dec 23 '25 13:12

Ádám Révész



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!