Created
February 23, 2023 06:30
-
-
Save aerphanas/b34ff6840b3189147716351251ba5a28 to your computer and use it in GitHub Desktop.
GetOpts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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