Skip to content

Instantly share code, notes, and snippets.

@nicolasff
Created April 13, 2011 17:48
Show Gist options
  • Save nicolasff/918004 to your computer and use it in GitHub Desktop.
Save nicolasff/918004 to your computer and use it in GitHub Desktop.
Grouping numbers together in Haskell
-- Group blocks together.
import Data.List (intersperse)
grp :: [Int] -> [(Int,Int)]
grp [] = []
grp (x:xs) = pair x x xs where
pair lo hi (x:xs) | x == hi + 1 = pair lo x xs
pair lo hi xs | otherwise = (lo,hi): grp xs
displayGroup :: [(Int,Int)] -> String
displayGroup = concat . intersperse "," . map displayPair where
displayPair (x,y) = if x == y then show x
else show x ++ "-" ++ show y
{-|
> grp [1,2,3,4,5,8,9,20,21,22,23,24,25,30]
[(1,5),(8,9),(20,25),(30,30)]
> displayGroup $ grp [1,2,3,4,5,8,9,20,21,22,23,24,25,30]
"1-5,8-9,20-25,30"
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment