[Haskell-cafe] ReadP - take first succesful parser ?

Marc Weber marco-oweber at gmx.de
Wed Apr 4 05:31:08 EDT 2007


Brief:
I want to make the parser 
    choice [string "dummy", anystring ]
	where anystring = many get

return the first match. 
(Thus if "dummy" matches disregarg all following
parsers)
..)

details:

I want to parse some wmii events.
They all look this way
ClientFocus 2
ClientFocus 2
LeftBarClick 1 web

At this moment I only need two of them (FocusTag and UnfocusTag)
So I've created the data type

type O = String
data WMIIEvent = FocusTag Int
                | UnfocusTag Int
		| Unkown String -- to be implemented

Now I want to create a simple ReadP parser which looks like this:

============= parser code ============================================
instance Read WmiiEvent where
  readsPrec _ = readP_to_S (foldr1 takeFirst
		[ rp "FocusTag" FocusTag
		, rp "UnfocusTag" UnfocusTag
		, rpUnkown ])
    where rp str f = fmap f $ string str >> skipSpaces >> liftM read (many get)
	  rp :: (Read a) => String -> (a -> WmiiEvent) -> ReadP WmiiEvent
	  rpUnkown = (many get) >>= return . Unkown
	  rpUnkown :: ReadP WmiiEvent

But I'm getting an ambiguous parse. (because "UnfocusTag 3" makes two
parsers of the choice list succeed.

How is this done?


More information about the Haskell-Cafe mailing list