RosettaCodeData/Task/Range-expansion/Haskell/range-expansion-3.hs

23 lines
607 B
Haskell
Raw Permalink Normal View History

2019-09-12 10:33:56 -07:00
{-# LANGUAGE FlexibleContexts #-}
import Control.Applicative (Applicative((<*>), (*>)), (<$>))
2015-02-20 00:35:01 -05:00
import Text.Parsec
2013-04-10 23:57:08 -07:00
2015-02-20 00:35:01 -05:00
expandRange :: String -> Maybe [Int]
expandRange = either (const Nothing) Just . parse rangeParser ""
2013-04-10 23:57:08 -07:00
2019-09-12 10:33:56 -07:00
rangeParser
:: (Enum a, Read a, Stream s m Char)
=> ParsecT s u m [a]
2015-02-20 00:35:01 -05:00
rangeParser = concat <$> (item `sepBy` char ',')
2019-09-12 10:33:56 -07:00
where
item = do
n1 <- num
n2 <- option n1 (char '-' *> num)
return [n1 .. n2]
num = read `dot` (++) <$> option "" (string "-") <*> many1 digit
dot = (.) . (.)
main :: IO ()
main = print $ expandRange "-6,-3--1,3-5,7-11,14,15,17-20"