Exercise solution: Parsing a comma-separated list

Contents
  • Exercise
  • Solution
    • listParser
    • listElementParser
    • unquotedElementParser
    • quotedElementParser
    • listElementParser revisited

Exercise

Write a parser for comma-separated values that can handle quoted strings. We’ve given you an outline with some blanks to fill in.

import Control.Applicative ((<|>), optional, many)

import Data.List.NonEmpty (NonEmpty ((:|)))
import qualified Data.List.NonEmpty as NE

listParser :: Parser (NonEmpty BS.ByteString)
listParser =
    do
        x <- _exercise_1

        xs <- many $
            do
                _exercise_2

        return (x :| xs)

listElementParser :: Parser BS.ByteString
listElementParser =
    _exercise_3

unquotedElementParser :: Parser BS.ByteString
unquotedElementParser =
    P.takeWhile _exercise_4

quotedElementParser :: Parser BS.ByteString
quotedElementParser =
    do
        _ <- P.string (ASCII.pack "\"")
        _exercise_5

Think carefully about which characters each parser can and cannot consume. Where are commas and spaces allowed, and where are they not? Where are quotation marks allowed?

Solution

Sign up for access to the full page, plus the complete archive and all the latest content.