
I'm trying to write a utility which is able to read Ratios from two distinct formats "2 / 3" -> 2 % 3 "4" -> 4 % 1 I'm sure that a skilled Haskell programmer could vastly improve on my code (do I even need Parsec?), so I've come to solicit advice. import Text.ParserCombinators.Parsec import qualified Text.ParserCombinators.Parsec.Token as P import Text.Parsec.Language (haskellDef) import Data.Ratio readFraction :: String -> Either ParseError (Ratio Integer) readFraction = parse ratio "-" lexer = P.makeTokenParser haskellDef integer = P.integer lexer natural = P.natural lexer whiteSpace = P.whiteSpace lexer ratio = try frac <|> integer' integer' = do i <- integer return $ fromInteger i frac = do whiteSpace num <- natural char '/' den <- integer return (num % den) f = readFraction " 3 / 2 " i = readFraction " 6 " main = print [f,i]

The avoiding /try/ is a good part of Parsec golf. Because turning natural literals into fractions is easy (%1) it is simple to use the /option/ parser to parse a suffix or return a default. /symbol/ is also a valuable parser, often preferable to /char/ or /string/ as it chomps trailing white space. symbol = P.symbol lexer fraction :: Parser Rational fraction = do num <- integer den <- option 1 (symbol "/" >> natural) return (num % den)
participants (2)
-
Jacek Generowicz
-
Stephen Tetley