0
votes

so I can't get my head around this problem:

I have the following code:

   data Number = NumberInt Integer
                | NumberFloat Double
                deriving(Show, Eq)


   intParser :: Parser Integer
    --code of the parser

   doubleParser :: Parser Double
    --code of the parser

   intOrFloat :: Parser Number
   intOrFloat = -- to do

one of my approaches was to implement the intOrFloat the following way:

intOrFloat :: Parser Number
intOrFloat =
      (do
        e<- doubleParser
        let result = (e :: Number)
        pure result)
      <|>
      (do
        f<- intParser
        let result = (f :: Number)
        pure result

      )

But I always end up with the error: Couldn't match expected type ‘Number’ with actual type ‘Integer’

Could somebody please explain me how to combine the two parsers to a new parser with another type ? I don't understand what the problem is. I am using parsec.

I am new to Haskell so please be gentle. Thank you.

1

1 Answers

1
votes

You can't simply cast the value to call it a Number; you have to construct a new value of type Number.

do
    e <- DoubleParser  -- e :: Double, assuming success
    let result = NumberFloat e  -- result :: Number
    pure result

The above can simply be written as

NumberFloat <$> DoubleParser

In full,

intOrFloat :: Parser Number
intOrFloat = NumberFloat <$> doubleParser <|> NumberInt <$> intParser