Search code examples
haskellparsec

How can I make an if using parsec (Haskell) to verify the input generated by an optional choice?


I have this algebraic datatype:

data Arithmetic = Sum Int Int | Mult Int Int
    deriving (Show)

And I want to do this:

parseArith :: Parser Arithmetic
parseArith = do
    a <- many1 digit
    spaces
    string "+" <|> string "*"
    spaces
    b <- many1 digit
    ...

Where on the "...", I would verify whether it has a "+" or a "*", can someone help me?


Solution

  • As a slight alternative to Franky's answer, make your choice return the constructor you need later on.

    parseArith :: Parser Arithmetic
    parseArith = do
        a <- many1 digit
        spaces
        op <- (string "+" >> return Sum)
          <|> (string "*" >> return Mult)
        spaces
        b <- many1 digit
        spaces
        return $ op (read a) (read b)