Exercise solution: Parsing a comma-separated list

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


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 =
        x <- _exercise_1

        xs <- many $

        return (x :| xs)

listElementParser :: Parser BS.ByteString
listElementParser =

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

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

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?


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