Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can there be an ambiguous parse using reads?

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?

like image 411
Ana Avatar asked Feb 18 '16 06:02

Ana


People also ask

Which parsing can be used to handle parsing ambiguities?

LR parser can be used to parse ambiguous grammars.

Can bottom up parser parse ambiguous grammar?

1 Answer. No parser can parse the ambiguous grammar .


1 Answers

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 <++.

like image 58
Vektorweg Avatar answered Sep 20 '22 13:09

Vektorweg