Search code examples
parsinghaskelltext-parsing

Mixing identifier parse with whitespace parser


The parsing library has the function identifier and the function whitespace:

identifier :: Parser Char String

whitespace :: Parser Char ()

The function identifier made the parsing of an identifier, but don't discard the whitespaces on the input text. So, we have the withespace function, that consumes all whitespaces from an input.

I was wondering if I could mix this two functions into one. Just like:

identifier' :: Parser Char String

However, I'm new in Haskell and don't know how I do that exactly. Is there a way to do that?


Solution

  • You can work with (<*) :: Applicative f => f a -> f b -> f a that will here run the first parser, then the second and return the result of the first parser, so:

    identifier' :: Parser Char String
    identifier' = identifier <* whitespace

    This is equivalent to:

    identifier' :: Parser Char String
    identifier' = do
        idf <- identifier
        whitespace
        return idf