Search code examples
haskellparsec

Haskell parsec parsing to maybe


Just a simple question that I cannot solve.

I want to parse a string as either a String or a Maybe Double, where an empty string or an "n/a" is parsed as a Nothing. For example something like:

data Value = S String | N (Maybe Double)

value::CharParser () Value
value = val <* spaces
    where val = N <$> v_number
           <|> S <$> v_string
           <|> N <$> v_nothing

I am having trouble with the v_nothing (and also leading and training white space).

Thanks.

EDIT:

v_number :: CharParser () (Maybe Double)
v_number = do s <- getInput
          case readSigned readFloat s of
            [(n, s')] -> Just n <$ setInput s'
            _         -> empty

v_string :: CharParser () String
v_string = (many1 jchar)
    where jchar = char '\\' *> (p_escape <|> p_unicode)
          <|> satisfy (`notElem` "\"\\")                

I tried all sort sorts of things for v_nothing to no avail.


Solution

  • Maybe something like this?

    value = do skipMany space
               choice $ map try [
                do string "n/a" <|> (eof >> return [])
                   return $ N Nothing,
                do d <- many digit
                   return $ N $ Just (read d)
                -- do ...       
                                ]