import Data.List (sort,tails) isAscP x y | succ x == y = True isAscP x y | x == '9', y == '0' = True isAscP _ _ = False isDescP x y | succ y == x = True isDescP x y | x == '0', y == '9' = True isDescP _ _ = False take2While :: (a -> a -> Bool) -> [a] -> [a] take2While _ [] = [] take2While _ (x:[]) = [x] take2While p (x:xs@(y:ys)) | p x y == True = x : take2While p xs | otherwise = [x] longestSeq p s = last . sort . map (\x -> (length x, x)) . map (take2While p) $ tails s longestAsc s = longestSeq isAscP s longestDesc s = longestSeq isDescP s main = do mapM_ print $ map ( \x -> last $ sort [ longestAsc x, longestDesc x ] ) test_data test_data = ["461771621368210983721913243963580233112903255149955120374576", "412182871611285727937329810487417347645678899662426008558163", "806445168622715729854145415356850576789033724164441981190358", "737993205942843210944632043755783070487691419376068748520835", "797836732611301651049157941402677493925908901268033467721123", "800343673335834413425690063499636965547527671535789010360222", "364556954738232740095412905428192849218058869868234154321153", "656886016318465389850845261620694916565611559209695154321950", "439823085483918818243602360632486757938483367890464586909210", "275010825726438419734041987657085162773815821872771619322197", "362862003186986435628956392997462270571538785287890111165953", "865788969800483978909876396956896428059483834654443783640994", "084943262444682256649196170826699756789404699917511813404654", "038022435612197850835139478901471838789042407199858583654421", "244712325541896615697820925442735727638540309574604984321042", "799272593665633014792964321006295907297545039391442339309443", "875134840933937552505069624569692178901372764210973501240868", "160604373233208765433548554842941708483446447649679473623104", "787966403724853567890040276258105492183424704761915858524942", "234565329824361008677075492264130762647177370538202678949041" ] #### $ runhaskell ascruns.hs (5,"21098") (5,"45678") (5,"67890") (6,"432109") (5,"89012") (5,"78901") (5,"54321") (5,"54321") (5,"67890") (5,"98765") (5,"78901") (5,"09876") (5,"56789") (5,"78901") (5,"43210") (5,"43210") (5,"78901") (6,"876543") (6,"567890") (5,"23456") #### longestSeq p s = maximum tuples where ts = tails s runs = map (take2While p) ts tuples = zip3 (map length runs) [0..] runs $ runhaskell ascruns.hs | head -n 4 (len,pos,str) (5,12,"21098") (5,37,"45678") (5,35,"67890")