The Standard Haskell Classes page says the following about reads :: (Read a) => String -> [(a,String)]
:
Normally, a parser returns a singleton list, containing a value of type a that was read from the input string and the remaining string that follows what was parsed. If no parse was possible, however, the result is the empty list, and if there is more than one possible parse (an ambiguity), the resulting list contains more than one pair.
Under what situations or examples does this ambiguity manifest?
LR parser can be used to parse ambiguous grammars.
1 Answer. No parser can parse the ambiguous grammar .
import Text.Read
data Foo = Bar Int | Baz Double deriving Show
instance Read Foo where
readPrec = fmap Bar readPrec +++ fmap Baz readPrec
In this example, the parser tries to parse Int
and Double
. If it can be parsed for both, the parser returns two values.
Resulting in:
> read "4" :: Foo
*** Exception: Prelude.read: ambiguous parse
and
> reads "4" :: [(Foo,String)]
[(Bar 4,""),(Baz 4.0,"")]
The easiest way here to fix ambiguity is to select one parse by replacing the choice operator +++
with the selective choice <++
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With