Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module SuccGroups where
- import Control.Arrow ((&&&), first)
- import Data.Function (on)
- import Data.List
- -- | Given two enumerable values, test whether the latter is the successor of
- -- the former.
- enumSucc :: (Enum a, Eq a) => a -> a -> Bool
- enumSucc a b = succ a == b
- -- | Return the starting index and the length of the item returned by succSpans
- -- with the highest length.
- --
- -- Given [0,1,10,11,12,14,20,21] and the predicate enumSucc, return (2,3).
- maxSuccBy :: (a -> a -> Bool) -> [a] -> (Integer, Integer)
- maxSuccBy p = maximumBy (compare `on` snd) . succSpansBy p
- -- | Return the starting indices and the lengths of the sublists returned by
- -- succGroupIndBy.
- --
- -- Given [0,1,10,11,12,14,20,21] and the predicate enumSucc, return
- -- [(0,2),(2,3),(5,1),(6,2)].
- succSpansBy :: (a -> a -> Bool) -> [a] -> [(Integer, Integer)]
- succSpansBy p = map (fst . head &&& genericLength) . succGroupIndBy p
- -- | Zip the input list with indices and call succGroupBy with the predicate p
- -- on the original, pre-zip value.
- --
- -- Given [0,1,10,11,12,14,20,21] and the predicate enumSucc, return
- -- [[(0,0),(1,1)], [(2,10),(3,11),(4,12)], [(5,14)], [(6,20),(7,21)]].
- succGroupIndBy :: (a -> a -> Bool) -> [a] -> [[(Integer, a)]]
- succGroupIndBy p = succGroupBy (p `on` snd) . zip [0..]
- -- | Return the groups of those items where each pair matches the predicate p.
- --
- -- Given [0,1,10,11,12,14,20,21] and the predicate enumSucc, return [[0,1],
- -- [10,11,12], [14], [20,21]].
- succGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
- succGroupBy p xs@(_:_) = as:succGroupBy p bs
- where (as, bs) = succSpanBy p xs
- succGroupBy _ [] = []
- -- | Return (as,bs) where as is the list of those items where each pair matches
- -- the predicate p and bs is the rest of the list.
- --
- -- Given [0,1,10,11,12,14,20,21] and the predicate enumSucc, return
- -- ([0,1], [10,11,12,14,20,21]).
- succSpanBy :: (a -> a -> Bool) -> [a] -> ([a], [a])
- succSpanBy p (x0:xs@(x1:_))
- | p x0 x1 = first (x0:) . succSpanBy p $ xs
- | otherwise = ([x0], xs)
- succSpanBy _ xs@[_] = (xs, [])
- succSpanBy _ [] = ([], [])
Add Comment
Please, Sign In to add comment