haskelloptparse-applicative

Parsing "enum" options with optparse-applicative


How do I implement a parser for this example from grep --help:

 --binary-files=TYPE   assume that binary files are TYPE;
                       TYPE is 'binary', 'text', or 'without-match'

Assuming that I have

data BinaryFiles = Binary | Text | WithoutMatch

How do I write a parser? option auto seems a kludge since Read is supposed to be an "inverse" to Show, and I'd like to keep the derived instance Show BinaryFiles.


Solution

  • Use str instead of auto:

    binFile :: ReadM BinaryFiles
    binFile = str >>= \s -> case s of
        "binary"        -> return Binary
        "text"          -> return Text
        "without-match" -> return WithoutMatch
        _ -> readerError "Accepted binary file types are 'binary', 'text', and 'without-match'."