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

前端 未结 2 1501
别那么骄傲
别那么骄傲 2020-12-21 17:43

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] ->          


        
相关标签:
2条回答
  • 2020-12-21 18:21

    You can use group and maximum

    import Data.List
    maxSeqLength :: Eq a => [a] -> Int
    maxSeqLength [] = 0
    maxSeqLength xs = (maximum . map length . group) xs
    
    0 讨论(0)
  • 2020-12-21 18:35

    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.

    0 讨论(0)
提交回复
热议问题