How to have fixed options using Option.Applicative in haskell?

43 Views Asked by At

Lets say I am building an interface with the following command:

$ run --display (file/env/db) # default to file if invalid is entered

What I am looking for specifically is how to obtain an enum value with the following:

Given:

data type = File | Env | Db

When the command run --display file is entered, the enum File is returned.

As far as I know, the strOption and strArgument functions are used for any arbitrary string argument. I have read the complete documentation but couldn't figure out any easy solution for this. Any help would be appreciated.

1

There are 1 best solutions below

0
willeM_ Van Onsem On

You can work with a custom parser, like:

import Data.Char(toLower)
import Options.Applicative(ReadM, eitherReader)

data OutputType = File | Env | Db

parseOutputType :: ReadM OutputType
parseOutputType = eitherReader $ (go . map toLower)
  where go "file" = Right File
        go "env" = Right Env
        go "db" = Right Db
        go _ = Left "Enter a valid option: file, env, or db"

and then parse the options with:

import Options.Applicative

data MyOptions = MyOptions { display :: OutputType }

parseOptions :: Parser MyOptions
parseOptions = MyOptions <$> option parseOutputType (long "display")