[Haskell-beginners] parsec question

Magnus Therning magnus at therning.org
Mon Jul 19 02:25:09 EDT 2010


On 19/07/10 04:36, Michael Mossey wrote:
> data Command = Play Int [Int]
>              | Jump Int
> 
> -- I want to parse a string that will have any of the following forms
> -- and turn it into Command
> --  "p"   - Produces "Play 0 []"
> --  "p v55" - Produces "Play 55 []"
> --  "p c123" - Produces "Play 0 [1,2,3]"
> --  "p v13 c12" - Produces "Play 13 [1,2]"
> 
> -- In other words the p command can have two kinds of arguments, "v"
> -- and "c", and there are defaults for the case that no argument is
> -- supplied.
> -- So it's going to look something like
> 
> play :: Parser Command
> play = do char 'p'
>           vResult <- .. maybe a v, otherwise supply default value 0
>           cResult <- .. maybe a c ..
>           (could the v and c be put in either order?)
>           return $ Play vResult cResult

This isn't really an answer, but more of a suggestion on how to approach
parsing problems.

I tend to split things until I get down to easily handled stuff.  In
this case
I'd probably write the following functions:

 1. Parser for strings like "v55" and "v13": result type Parser Int
 2. Parser for strings like "c123" and "c12": result type Parser [Int]
 3. Parser combining 1 and 2: result type Parser (Int, [Int])
 4. Parser requiring a string starting with 'p ', combined with 3:
result type
    Parser Command

/M

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 262 bytes
Desc: OpenPGP digital signature
Url : http://www.haskell.org/pipermail/beginners/attachments/20100719/81187a78/signature.bin


More information about the Beginners mailing list