Reputation: 165
agrupa :: String -> [(Char,Int)]
agrupa [ ] = [ ]
agrupa (x:xs) = let (l1, l2) = span' (==x) xs
in (x, (length l1) + 1) : agrupa l2
span' :: (a->Bool) -> [a] -> ([a],[a])
span' p l = (takeWhile p l, dropWhile p l)
this function gets a string and gives us how many of each character are there?
my question is related to the 1
in (length l1) + 1
why do we need it?
I'd really appreciate if you explain it with different example because such cases (like+1) I've seen lots of times also in scan( or debug only the agrope part please) the function to see how it works exactly?
thanks for your time
Upvotes: 0
Views: 108
Reputation: 120711
The + 1
is there because you've previously matched one of the == x
elements away, namely x
itself, in the pattern (x:xs)
. If you didn't consider that, a list with no duplicates would give all 0
s in the snd
of each tuple in the result; as you have it the snd
always gives the actual number of consecutive elements.
Upvotes: 6