Skip to content

Instantly share code, notes, and snippets.

@hellertime
Created November 12, 2010 21:02
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 hellertime/674679 to your computer and use it in GitHub Desktop.
Save hellertime/674679 to your computer and use it in GitHub Desktop.
compute the bounds of consecutive intervals along an enumeration
intervals :: (Eq a, Enum a) => [a] -> [(a, Maybe a)]
intervals [] = []
intervals (x:[]) = [(x, Nothing)]
intervals (x:xs) = (x, lastSuccessor x x xs) : intervals (dropSuccessors x xs)
where
lastSuccessor :: (Eq a, Enum a) => a -> a -> [a] -> Maybe a
lastSuccessor l x []
| l == x = Nothing
| otherwise = Just x
lastSuccessor l x (y:ys)
| succ x == y = lastSuccessor l y ys
| otherwise = lastSuccessor l x []
dropSuccessors :: (Eq a, Enum a) => a -> [a] -> [a]
dropSuccessors x [] = []
dropSuccessors x done@(y:ys)
| succ x == y = dropSuccessors y ys
| otherwise = done
@hellertime
Copy link
Author

see gist https://gist.github.com/674538 for a Python version of this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment