I am reading Programming In Haskell, in the 8th chapter, the author gives an example of writing parsers.
The full source is here: http://www.cs.nott.ac.uk/~gmh/Parsing.lhs
I can’t understand the following part: many permits zero or more applications of p,
whereas many1 requires at least one successful application:
many :: Parser a → Parser [a ]
many p = many1 p +++ return [ ]
many1 :: Parser a → Parser [a ]
many1 p = do v ← p
vs ← many p
return (v : vs)
How the recursive call happens at
vs <- many p
vs is the result value of many p, but many p called many1 p, all many1 has in its definition is a do notation, and again has result value v, and vs, when does the recursive call return?
Why does the following snippet can return [("123","abc")] ?
> parse (many digit) "123abc"
[("123", "abc")]
For the last question:
Means that parsing has been successful as at least one result has been returned in the answer list. Hutton parsers always return a list – the empty list means parsing failure.
The result (“123”, “abc”) means that parsing has found three digits “123” and stopped at ‘a’ which is not a digit – so the “rest of the input” is “abc”.
Note that
manymeans “as many as possibly” not “one or more”. If it were “one or more” you’d get this result instead:This behaviour wouldn’t be very good for deterministic parsing, though it might sometimes be needed for natural language parsing.