Command Line Flags in Idris
Here’s the translation of the Go code to Idris, formatted in Markdown suitable for Hugo:
Our first program will demonstrate how to handle command-line flags in Idris. Here’s the full source code:
module Main
import System
import Data.String
-- Define a record to hold our flag values
record Flags where
constructor MkFlags
word : String
numb : Int
fork : Bool
svar : String
-- Parse command-line arguments into our Flags record
parseFlags : List String -> Flags
parseFlags args = parseHelper args (MkFlags "foo" 42 False "bar")
where
parseHelper : List String -> Flags -> Flags
parseHelper [] flags = flags
parseHelper (arg :: rest) flags =
case arg of
"--word=" ++ w => parseHelper rest (record { word = w } flags)
"--numb=" ++ n => parseHelper rest (record { numb = cast n } flags)
"--fork" => parseHelper rest (record { fork = True } flags)
"--svar=" ++ s => parseHelper rest (record { svar = s } flags)
_ => parseHelper rest flags
main : IO ()
main = do
args <- getArgs
let flags = parseFlags (drop 1 args) -- drop the program name
putStrLn $ "word: " ++ flags.word
putStrLn $ "numb: " ++ show flags.numb
putStrLn $ "fork: " ++ show flags.fork
putStrLn $ "svar: " ++ flags.svar
putStrLn $ "tail: " ++ show (drop 5 args) -- show remaining args
To experiment with the command-line flags program, first compile it and then run the resulting executable directly.
$ idris -o command-line-flags command-line-flags.idr
Try out the built program by first giving it values for all flags.
$ ./command-line-flags --word=opt --numb=7 --fork --svar=flag
word: opt
numb: 7
fork: True
svar: flag
tail: []
Note that if you omit flags, they automatically take their default values.
$ ./command-line-flags --word=opt
word: opt
numb: 42
fork: False
svar: bar
tail: []
Trailing positional arguments can be provided after any flags.
$ ./command-line-flags --word=opt a1 a2 a3
word: opt
...
tail: ["a1", "a2", "a3"]
In this Idris implementation, we’ve created a simple parser for command-line arguments. Unlike Go’s flag
package, Idris doesn’t have a built-in command-line flag parsing library in its standard library. Therefore, we’ve implemented a basic version ourselves.
The Flags
record holds our flag values, and the parseFlags
function processes the command-line arguments to populate this record. The main
function then uses these parsed values.
Note that this implementation is more basic than Go’s flag
package. It doesn’t automatically generate help text or handle errors for undefined flags. For a more robust command-line parsing solution in Idris, you might want to look into third-party libraries or implement more advanced parsing logic.