EntryPoint, Command-Line Arguments
This page was last reviewed on Nov 23, 2023.
Dot Net Perls
EntryPoint. An F# program must start somewhere—we can use the EntryPoint type annotation for this purpose. EntryPoint designates the initial method of a program.
With this attribute, a method is executed at program initiation. And any arguments to the command-line are passed as a string array to the program.
This program specifies a main function, and uses the EntryPoint type annotation upon it. When we run the program with "dotnet run" main is executed.
Step 1 With a for-do loop, we iterate over the arguments passed after the "dotnet run" command.
Step 2 Inside a string interpolation expression, we invoke the formatArgument function on each string argument.
Step 3 In formatArgument, we call 2 separate functions in a pipeline on the argument.
Step 4 This function (spaceOut) spaces out the argument string with some string logic involving a char array.
Step 5 We write the length of the arguments array (argv) which is 2 in this case (the program's file name is not included in the array).
Step 6 For the main method, we are supposed to return an integer value to indicate success—0 is acceptable.
let uppercase (argument : string) = argument.ToUpper() let spaceOut (argument : string) = // Step 4: place a space in between each character. let mutable chars = Array.create (argument.Length * 2) ' ' for i = 0 to argument.Length - 1 do chars[i * 2] <- argument[i] new string(chars) let formatArgument (argument : string) = // Step 3: call pipelined functions to format an argument. argument |> uppercase |> spaceOut [<EntryPoint>] let main argv = // Step 1: loop over arguments to program. for arg in argv do // Step 2: format each argument with a function. printfn $"ARG IS {formatArgument(arg)}" // Step 5: write the Length. printfn $"LENGTH: {argv.Length}" // Step 6: return 0. 0
dotnet run argument1 argument2 ARG IS A R G U M E N T 1 ARG IS A R G U M E N T 2 LENGTH: 2
Indeterminate type error. Consider this F# compile error—it occurs when a program has no EntryPoint. We can correct the problem with an EntryPoint type annotation.
.../Program.fs(23,24): error FS0072: Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of the object. This may allow the lookup to be resolved.
Many F# programs that are used in the real world will be command-line applications. They receive arguments, and print out values (or write files).
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 23, 2023 (new).
© 2007-2024 Sam Allen.