Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurrence of an element in Haskell list and return max sequence

Tags:

list

haskell

I have the following code to count the occurrence of an element in a Haskell list:

data Elem = Vanilla | Choco deriving (Eq,Show)
maxStarSeq :: [Elem] -> Int
maxStarSeq [] = 0
maxStarSeq (Vanilla:xs) = 0 + maxStarSeq xs
maxStarSeq (Choco:xs) = 1 + maxStarSeq xs

Now, how can I return the max sequence of that element, instead of an absolute counter? I mean, let's say that my list is:

[Vanilla,Choco,Choco,Vanilla,Choco]

With my code, I will get 3 because there are 3 Choco characters in the list. What I want is to get 2, because that is the max sequence of Choco characters, while the next sequence is shorter.

What I need is some way to make a comparison between the sequences, to evaluate which is longer, or something like that.

like image 411
noobsharp Avatar asked Dec 07 '25 02:12

noobsharp


2 Answers

You can use group and maximum

import Data.List
maxSeqLength :: Eq a => [a] -> Int
maxSeqLength [] = 0
maxSeqLength xs = (maximum . map length . group) xs
like image 124
Lee Avatar answered Dec 08 '25 23:12

Lee


You can use worker wrapper pattern to achieve your required result:

maxStarSeq :: [Elem] -> Int
maxStarSeq xs = aux xs 0 0
    where aux [] acc prev = max acc prev
          aux (Vanilla:xs) acc prev = aux xs (max acc prev) 0
          aux (Choco:xs) acc prev = aux xs acc (prev + 1)

The prev parameter will track the current number of consecutive Choco parameters. The acc parameter will have the maximum number of Choco parameters for it's previous run. It's value will be updated each time you encounter Vanilla value.

like image 40
Sibi Avatar answered Dec 08 '25 21:12

Sibi