[Haskell-cafe] Am I using Parsec correctly?
Mario Blažević
blamario at ciktel.net
Fri Mar 6 02:12:41 UTC 2015
On 03/03/15 05:00 AM, Cody Goodman wrote:
> -- trying to parse the text below using Parsec:
>
> -- ACT I.
>
> -- SCENE I. An open place.
> -- [An open place. Thunder and lightning. Enter three Witches.]
>
> -- FIRST WITCH.
> -- When shall we three meet again
> -- In thunder, lightning, or in rain?
>
> -- Here's the code I have
>
> import Text.Parsec
> import Control.Applicative
> import Data.Traversable (sequenceA)
>
> section s = sequenceA [string s, string " ", many1 letter] `endBy`
> char '.'
>
> act = section "ACT"
> scene = section "SCENE"
>
> main = do
> parseTest act "ACT I.\n"
> parseTest scene "SCENE I."
>
> -- this returns:
> -- λ> main
> -- [["ACT"," ","I"]]
> -- [["SCENE"," ","I"]]
>
> -- Am I using Parsec correctly so far?
The act, scene, and section functions are just fine. The main
function is probably not, unless you really intend your act and scene to
be two different inputs. The parseTest function should generally be used
only once, and it should be applied to the entire parser. So what you
want is more like
> parser = do act
> string "\n"
> scene
>
> main = parseTest parser "ACT I.\nSCENE I."
Note that the result of the act function is being discarded in this
example. You'll probably want to preserve it somehow, but unless you
just want to print it you'll need to decide what kind of result you want
to construct. It's generally a good idea to do that before setting out
to write the parser itself.
More information about the Haskell-Cafe
mailing list