[Haskell-cafe] Parsers for Text Adventures

Iavor Diatchki iavor.diatchki at gmail.com
Sun Jan 17 13:33:26 EST 2010


Hi Mark,

On Sun, Jan 17, 2010 at 5:30 AM, Mark Spezzano
<mark.spezzano at chariot.net.au> wrote:
> Question: Am I going about this the right way? I want to put together lots of "data" types like Verb and Noun etc so that I can build a kind of "BNF grammar".

Your basic idea to use a datatype is a good one.  You just need to
implement it in a slightly different way.  For example, you could
write a function:

string :: String -> Parser ()

Given a string, this function returns a parser that will try to
recognize the string in the input.  If successful, the parser returns
a single trivial result, otherwise it fails (i.e. returns an empty
list of result).

You will also need a function, say (<+>):

(<+>) :: Parser a -> Parser a -> Parser a

This function will apply two parser two the same input and combine
their results.  Now you can write your verb parser:


verb :: Parser Verb
verb = (string "jump" >> return Jump)
     <+>
           ((string "get" <+> string "take") >> return Get)   --
supports synonyms
    <+>
  ... etc ..

Hope that this helps.
-Iavor
PS: By the way, there are a number of libraries that already implement
such basic "parser combinators" so you can use one of them if you are
not interested in the actual low level details of how the parser
works.  One such library is "parsimony", another is "parsec".








> Question: If I am going about this the right way then what do I about the "read x" bit failing when the user stops typing in a recognised keyword. I could catch the exception, but typing an incorrect sentence is just a typo, not really appropriate for an exception, I shouldn't think. If it IS appropriate to do this in Haskell, then how do I catch this exception and continue processing.


More information about the Haskell-Cafe mailing list