Range expansion: Difference between revisions

→‎Haskell – With a parser: Added FlexibleContents to enable parsing, applied hlint, hindent
(Add Factor example)
(→‎Haskell – With a parser: Added FlexibleContents to enable parsing, applied hlint, hindent)
Line 1,425:
where (a, b) = break (== delim) l</lang>
===With a parser===
<lang haskell>import{-# Control.ApplicativeLANGUAGE (Applicative((<*>),(*>)),(<$>))FlexibleContexts #-}
 
import Control.Applicative (Applicative((<*>), (*>)), (<$>))
import Text.Parsec
 
expandRange :: String -> Maybe [Int]
expandRange = either (const Nothing) Just . parse rangeParser ""
 
rangeParser :: Parser [Int]
:: (Enum a, Read a, Stream s m Char)
=> ParsecT s u m [a]
rangeParser = concat <$> (item `sepBy` char ',')
where item = do n1 <- num
item = do
n2 <- option n1 (char '-' *> num)
return [n1 ..<- n2]num
n2 <- numoption ::n1 Parser(char Int'-' *> num)
return [n1 .. n2]
num = read `dot` (++) <$> option "" (string "-") <*> many1 digit
num = read `dot =` ((.++). <$> option "" (.)string "-") </lang*> many1 digit
dot = (.) . (.)
 
main :: IO ()
main = print $ expandRange "-6,-3--1,3-5,7-11,14,15,17-20"</lang>
{{Out}}
<pre>Just [-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20]</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
9,655

edits