[Haskell-cafe] mapAccumL - find max in-sequence subsequence

Sebastian Sylvan sylvan at student.chalmers.se
Sat Oct 28 18:51:12 EDT 2006


On 10/28/06, jim burton <jim at sdf-eu.org> wrote:
>
> I need to find the length of the longest in-sequence section of a list of
> ints...I am guessing something like mapAccumL is the way but not sure how.
>
> --this doesn't work
> Prelude List> mapAccumL (\x y -> if y==(x+1) then (y, x) else (y,0)) 0 $
> sort $  nub [9, 1, 2, 7, 3, 4, 5, 6,5]
> (9,[0,1,2,3,4,5,6,0])
>

I'm not sure I completely understand what you want, and if it needs to
be "cute" (i.e. some clever one liner usage of a library function).
But here's my "get-the-job-done-solution" (assuming I understood what
you want):

import Data.List
import Data.Ord

longestInSequence :: (Enum a) => [a] -> Int
longestInSequence = maximum . map (length . takeInSeq) . tails

takeInSeq []  = []
takeInSeq [x] = [x]
takeInSeq (x:y:xs) | fromEnum (succ x) == fromEnum y = x : takeInSeq (y:xs)
			 | otherwise   = takeInSeq (x:xs)

/S
-- 
Sebastian Sylvan
+46(0)736-818655
UIN: 44640862


More information about the Haskell-Cafe mailing list