Command Line Flags in Haskell
Here’s the translation of the Go code example to Haskell, along with explanations in Markdown format suitable for Hugo:
In Haskell, we can create a simple command-line program that uses flags to specify options. We’ll use the optparse-applicative
library, which is a popular choice for parsing command-line arguments in Haskell.
First, let’s start with the necessary imports:
import Options.Applicative
import Data.Semigroup ((<>))
Now, let’s define a data structure to hold our command-line options:
data Options = Options
{ word :: String
, numb :: Int
, fork :: Bool
, svar :: String
}
Next, we’ll create a parser for our options:
optionsParser :: Parser Options
optionsParser = Options
<$> strOption
( long "word"
<> short 'w'
<> metavar "STRING"
<> help "A string"
<> value "foo" )
<*> option auto
( long "numb"
<> short 'n'
<> metavar "INT"
<> help "An int"
<> value 42 )
<*> switch
( long "fork"
<> short 'f'
<> help "A bool" )
<*> strOption
( long "svar"
<> short 's'
<> metavar "STRING"
<> help "A string var"
<> value "bar" )
Now, let’s create our main function:
main :: IO ()
main = do
opts <- execParser opts
putStrLn $ "word: " ++ word opts
putStrLn $ "numb: " ++ show (numb opts)
putStrLn $ "fork: " ++ show (fork opts)
putStrLn $ "svar: " ++ svar opts
where
opts = info (optionsParser <**> helper)
( fullDesc
<> progDesc "A command-line flags example"
<> header "command-line-flags - demonstrate command-line flag parsing" )
To use this program, you would compile it and then run it with various command-line options:
$ ghc -o command-line-flags command-line-flags.hs
$ ./command-line-flags --word=opt --numb=7 --fork --svar=flag
word: opt
numb: 7
fork: True
svar: flag
If you omit flags, they automatically take their default values:
$ ./command-line-flags --word=opt
word: opt
numb: 42
fork: False
svar: bar
You can also use the -h
or --help
flag to get automatically generated help text:
$ ./command-line-flags --help
command-line-flags - demonstrate command-line flag parsing
Usage: command-line-flags [-w|--word STRING] [-n|--numb INT] [-f|--fork]
[-s|--svar STRING]
A command-line flags example
Available options:
-w,--word STRING A string
-n,--numb INT An int
-f,--fork A bool
-s,--svar STRING A string var
-h,--help Show this help text
This Haskell version provides similar functionality to the original example, using the optparse-applicative
library to handle command-line argument parsing. The main differences are in the syntax and the way the parser is defined, but the overall structure and functionality remain the same.