I'm trying to parse a string, like
AA{A}{END}}
with given map: fromList [("{",43),("}",44),("{END}",255),("A",65)],
so that desired output is: [65,65,43,65,44,255,44]
It looks like searching for longest prefix in map in straight Haskell, but how do I parse it with Parsec? It is similar to this question, but here I should return Word8 value instead of string parsed by 'choice'.
You first need to write a parser that takes as input a
(Word8, Int)tuple and returns aParser Word8value.The above parser uses
tryagainst thestringparser because Parsec has the nasty habit of consuming matching characters even on fail. If thetry (string s)portion is successful, it returns theWord8value from the tuple.Now you can map your input list against that
keyValParserto build the parser you're looking for:Running this parser using
parseTestin GHCi yields:But wait! That's not quite right. The problem now is that
choicestops at the first matching parser, and the string{END}first matches{and thus returns43. You can fix this by ordering thelookupvalues by longest text first usingsortBy (flip $ comparing (length . fst)):Now you get the right results: