Created
April 13, 2011 17:48
-
-
Save nicolasff/918004 to your computer and use it in GitHub Desktop.
Grouping numbers together in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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