Home > Software engineering >  What do I have to change in my code to work?
What do I have to change in my code to work?

Time:11-03

I do not know what is the problem with my code. Can I get some help to understand it ?

Use longestChain to see how long the longest string in a text is made up of identical characters!

Examples:
 longestChain "2111234" == 3
 longestChain "0023212212222" == 4
 longestChain "23232323232" == 1
 longestChain "     !!!-------" == 7
longestChain :: String -> Int
longestChain (x:y:xs)
 | x == y = 1   longestChain xs
 | otherwise = longestChain (y:xs)

CodePudding user response:

> :m Data.List
Data.List> maximum $ map length $ group $ "     !!!-------"
7

group :: Eq a => [a] -> [[a]] is in Data.List.

"The group function takes a list and returns a list of lists such that the concatenation of the result is equal to the argument. Moreover, each sublist in the result contains only equal elements. "

map length returns a list with each sublist replaced by its length.

maximum returns the maximum of those lengths.

How did I find group? I searched Hoogle for a function with that signature.

CodePudding user response:

This isn't clean but it works.

longestChain :: String -> Int
longestChain [] = 0
longestChain xs = go xs 0 1 where
  go [] curr res = res
  go [x] curr res
    | curr > 0  = max (curr 1) res
    | otherwise = res
  go (x:y:xs) curr res
    | x == y = go (y:xs) (curr 1) (max (curr 1) res)
    | curr > 0 = go (y:xs) 0 (max (curr 1) res)
    | otherwise = go (y:xs) 0 res

It isn't enough to add one to the result of the function when we find similar characters. We need to calculate every chain in the string and return the longest length that we find. That's what curr and res take care of.

Also, when you find 2 characters matching, you need to add the second one to your list to match it with the next, otherwise you miss one. In addition, when you find a non-match, if you have your curr greater than 0, it means that this character belongs to the end of the previous chain, so you add one.

  • Related