Command Line Flags in F#

Here’s the translation of the Go code to F# with explanations in Markdown format suitable for Hugo:

In F#, we can use the System.Environment.GetCommandLineArgs() function to access command-line arguments. For more complex command-line parsing, we’ll use the Argu library, which is similar to Go’s flag package.

First, let’s install the Argu package:

dotnet add package Argu

Now, let’s create our command-line flags program:

open System
open Argu

type CLIArguments =
    | [<Mandatory>] Word of string
    | Numb of int
    | Fork
    | Svar of string
    interface IArgParserTemplate with
        member s.Usage =
            match s with
            | Word _ -> "a string"
            | Numb _ -> "an int"
            | Fork _ -> "a bool"
            | Svar _ -> "a string var"

[<EntryPoint>]
let main argv =
    let parser = ArgumentParser.Create<CLIArguments>(programName = "CommandLineFlags")
    let results = parser.Parse argv

    let word = results.GetResult Word
    let numb = results.GetResult(Numb, defaultValue = 42)
    let fork = results.Contains Fork
    let svar = results.GetResult(Svar, defaultValue = "bar")

    printfn "word: %s" word
    printfn "numb: %d" numb
    printfn "fork: %b" fork
    printfn "svar: %s" svar
    printfn "tail: %A" (results.GetResult(UnparsedArguments, defaultValue = []))

    0

In this F# program:

  1. We define a discriminated union CLIArguments to represent our command-line options.

  2. We implement the IArgParserTemplate interface to provide usage descriptions for each option.

  3. In the main function, we create an ArgumentParser and parse the command-line arguments.

  4. We then retrieve the values of our options using the GetResult method, providing default values where appropriate.

  5. Finally, we print out the parsed options and any trailing positional arguments.

To build and run the program:

dotnet build
dotnet run -- -word=opt -numb=7 --fork -svar=flag

This will output:

word: opt
numb: 7
fork: true
svar: flag
tail: []

You can omit flags to use their default values:

dotnet run -- -word=opt

Output:

word: opt
numb: 42
fork: false
svar: bar
tail: []

Trailing positional arguments can be provided after any flags:

dotnet run -- -word=opt a1 a2 a3

Output:

word: opt
numb: 42
fork: false
svar: bar
tail: ["a1"; "a2"; "a3"]

To get help text for the command-line program:

dotnet run -- --help

This will display automatically generated help text showing all available options and their descriptions.

The Argu library provides a robust way to handle command-line arguments in F#, offering functionality similar to Go’s flag package.