Skip to content

Instantly share code, notes, and snippets.

@nonowarn
Created September 17, 2009 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nonowarn/188534 to your computer and use it in GitHub Desktop.
Save nonowarn/188534 to your computer and use it in GitHub Desktop.
Finding repeatings in lists
import Prelude()
import Prelude.Plus
type Repeating = []
findRepeatings :: Eq a => [a] -> [Repeating a]
findRepeatings = concatMap findRepeatingsStartFromHere . tails
findRepeatingsStartFromHere :: Eq a => [a] -> [Repeating a]
findRepeatingsStartFromHere =
map fst
. filter (uncurry isPrefixOf)
. uncurry zip
. (tail . inits &&& tail . tails)
findRepeatingsWithIndices :: (Eq a) => [a] -> [(Int,Repeating a)]
findRepeatingsWithIndices =
concatMap (uncurry zip . (repeat *** findRepeatingsStartFromHere))
. zip [0..]
. tails
type Colony = []
allSublistOf :: [a] -> [[a]]
allSublistOf = ([]:) . (tails >=> tail . inits)
has :: (Eq a) => [a] -> a -> Int
has haystack needle = length . filter (==needle) $ haystack
findColony :: (Eq a) => a -> [a] -> Colony a
findColony needle haystack = let hasNeedle = (`has` needle) in
minimumBy (comparing length) . head
. groupBy ((==) `on` hasNeedle) . reverse . sortBy (comparing hasNeedle)
. allSublistOf $ haystack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment