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.
You can use group and maximum
import Data.List
maxSeqLength :: Eq a => [a] -> Int
maxSeqLength [] = 0
maxSeqLength xs = (maximum . map length . group) xs
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With