[Haskell-beginners] Parsec, comma sperated list with special last element

Daniel Trstenjak daniel.trstenjak at gmail.com
Sun Dec 16 18:42:26 CET 2012


Hi Nathan,

On Sun, Dec 16, 2012 at 05:55:53PM +0100, Nathan Hüsken wrote:
> cell = many1 (noneOf ",")
> lastCell = many1 (noneOf "\n")

I wouldn't define the cells by the character that separates them, but
by the allowed characters for a cell.


Using attoparsec with applicative style (I didn't yet use parsec) I would write:

import qualified Data.Attoparsec.Text as P
import qualified Data.Attoparsec.Combinator as PC
import qualified Data.Text as T
import Data.Char (isAlpha)

cell :: P.Parser T.Text
cell = P.takeWhile1 isAlpha

data Row {
   fstCell  :: T.Text,
   sndCell  :: T.Text,
   lastCell :: T.Text
   }

row :: P.Parser Row
row = Row <$> cell 
          <*> (P.char ',' *> cell) 
          <*> (P.char ',' *> cell)

rows :: P.Parser [Row]
rows = PC.manyTill row P.endOfLine


The applicative style really shines in these cases, because the
definition of the parser combines nicely with the creation of
the data structures for the parsed data.

Greetings,
Daniel



More information about the Beginners mailing list