Skip to content

Instantly share code, notes, and snippets.

@aerphanas
Created February 23, 2023 06:30
Show Gist options
  • Select an option

  • Save aerphanas/b34ff6840b3189147716351251ba5a28 to your computer and use it in GitHub Desktop.

Select an option

Save aerphanas/b34ff6840b3189147716351251ba5a28 to your computer and use it in GitHub Desktop.
GetOpts
import System.Console.GetOpt
import System.Environment
data Options = Options
{ optVerbose :: Bool
, optInputFile :: Maybe FilePath
, optOutputFile :: Maybe FilePath
} deriving (Show)
defaultOptions :: Options
defaultOptions = Options
{ optVerbose = False
, optInputFile = Nothing
, optOutputFile = Nothing
}
options :: [OptDescr (Options -> Options)]
options =
[ Option "v" ["verbose"] (NoArg (\opts -> opts { optVerbose = True })) "Verbose output"
, Option "i" ["input"] (ReqArg (\arg opts -> opts { optInputFile = Just arg }) "FILE") "Input file"
, Option "o" ["output"] (ReqArg (\arg opts -> opts { optOutputFile = Just arg }) "FILE") "Output file"
]
parseOptions :: [String] -> IO (Options, [String])
parseOptions argv =
case getOpt Permute options argv of
(o, n, []) -> return (foldl (flip id) defaultOptions o, n)
(_, _, errs) -> ioError (userError (concat errs ++ usageInfo header options))
where header = "Usage: my-program [OPTION...] files..."
main :: IO ()
main = do
args <- getArgs
(opts, nonOpts) <- parseOptions args
print opts
print nonOpts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment