[Haskell-cafe] parsing currency amounts with parsec

Eric Rasmussen ericrasmussen at gmail.com
Tue May 10 00:07:57 CEST 2011


Hi everyone,

I am relatively new to Haskell and Parsec, and I couldn't find any articles
on parsing numbers in the following format:

Positive: $115.33
Negative: ($1,323.42)

I'm working on the parser for practical purposes (to convert a 3rd-party
generated, most unhelpful format into one I can use), and I'd really
appreciate any insight into a better way to do this, or if there are any
built-in functions/established libraries that would be better suited to the
task. My code below works, but doesn't seem terribly efficient.

Thanks!
Eric

-------------------------------------------------
{- parses positive and negative dollar amounts -}

integer :: CharParser st Integer
integer = PT.integer lexer

float :: CharParser st Double
float = PT.float lexer

currencyAmount = try negAmount <|> posAmount

negAmount = do char '('
              char '$'
              a <- currency
              char ')'
              return (negate a)

posAmount = do char '$'
              a <- currency
              return a

currency = do parts <- many floatOrSep
             let result = combine orderedParts where
                   combine = sumWithFactor 1
                   orderedParts = reverse parts
             return result

floatOrSep = try float <|> beforeSep

beforeSep = do a <- integer
              char ','
              return (fromIntegral a :: Double)

sumWithFactor n []     = 0
sumWithFactor n (x:xs) = n * x + next
                        where next = sumWithFactor (n*1000) xs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20110509/4b68033f/attachment.htm>


More information about the Haskell-Cafe mailing list