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.
for-do
loop, we iterate over the arguments passed after the "dotnet run" command.string
interpolation expression, we invoke the formatArgument
function on each string
argument.formatArgument
, we call 2 separate functions in a pipeline on the argument.spaceOut
) spaces out the argument string
with some string
logic involving a char
array.argv
) which is 2 in this case (the program's file name is not included in the array).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.
0dotnet 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
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).