[Haskell-beginners] Parsing

David McBride toad3k at gmail.com
Fri Apr 14 18:17:42 UTC 2017


Try breaking it up into pieces.  There a literal "package" which is
dropped.  There is a first identifier, then there are the rest of the
identifiers (a list), then those two things are combined somehow (with
:).

literal "package" *> (:) <$> identifier <*> restOfIdentifiers
where
  restOfIdentifiers :: Applicative f => f [String]
  restOfIdentifiers = many ((:) <$> char '.' <*> identifier

I have not tested this code, but it should be close to what you are looking for.

On Fri, Apr 14, 2017 at 2:02 PM, mike h <mike_k_houghton at yahoo.co.uk> wrote:
> I have
> data PackageDec = Pkg String deriving Show
>
> and a parser for it
>
> packageP :: Parser PackageDec
> packageP = do
>     literal “package"
>     x  <- identifier
>     xs <- many ((:) <$> char '.' <*> identifier)
>     return $ Pkg . concat $ (x:xs)
>
> so I’m parsing for this sort  of string
> “package some.sort.of.name”
>
> and I’m trying to rewrite the packageP parser in applicative style. As a not quite correct start I have
>
> packageP' :: Parser PackageDec
> packageP' = literal "package" >>  Pkg . concat <$> many ((:) <$> char '.' <*> identifier)
>
> but I can’t see how to get the ‘first’ identifier into this sequence - i.e. the bit that corresponds to  x <- identifier        in the
> monadic version.
>
> in ghci
> λ-> :t many ((:) <$> char '.' <*> identifier)
> many ((:) <$> char '.' <*> identifier) :: Parser [[Char]]
>
> so I think that somehow I need to get the ‘first’ identifier into a list just after  Pkg . concat  so that the whole list gets flattened and everybody is happy!
>
> Any help appreciated.
>
> Thanks
> Mike
>
>
>
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners


More information about the Beginners mailing list