ZetCode

F# reading input and arguments

last modified December 3, 2026

In this article we read input from the user, from other programs and from the command line.

A program gets data from outside in three common ways. It reads standard input, which is the keyboard when we run it in a terminal, or another program or file when its input is redirected. It reads command line arguments, the words written after the program name. And it reads environment variables. F# uses the .NET Console and Environment classes for all three.

Reading a line

Console.ReadLine waits until the user types a line and presses Enter, and returns the line without the line break.

greet.fsx
open System

printf "Enter your name: "
let name = Console.ReadLine()

printfn "Hello there, %s!" name

The script asks for a name and greets the user.

printf "Enter your name: "

The prompt is printed with printf, not printfn, so the cursor stays on the same line and the user types after the colon.

λ dotnet fsi greet.fsx
Enter your name: Lucia
Hello there, Lucia!

Reading numbers

ReadLine always returns a string. To read a number we parse the line, and because the user may type anything, we use TryParse and ask again until the input is valid. Parsing is covered in F# type conversion.

numbers.fsx
open System

let readInt (prompt: string) =
    let mutable result = None
    while result.IsNone do
        printf "%s" prompt
        match Int32.TryParse(Console.ReadLine()) with
        | true, n -> result <- Some n
        | false, _ -> printfn "Please enter a whole number."
    result.Value

let width = readInt "Width: "
let height = readInt "Height: "

printfn "Area: %d" (width * height)

The readInt function repeats the prompt until the line is a valid integer.

while result.IsNone do

The loop runs while no number has been read. When parsing succeeds, the mutable result gets a value and the loop ends. In the run below the user mistypes the width twice.

λ dotnet fsi numbers.fsx
Width: 12m
Please enter a whole number.
Width: twelve
Please enter a whole number.
Width: 12
Height: 7
Area: 84

The end of input

When the input has no more lines, ReadLine returns null. In a terminal, the end of input is signalled with Ctrl+D on Linux and macOS, or Ctrl+Z and Enter on Windows. When the input comes from a pipe, it ends with the data.

count.fsx
open System

let mutable count = 0
let mutable total = 0
let mutable line = Console.ReadLine()

while not (isNull line) do
    count <- count + 1
    total <- total + line.Length
    line <- Console.ReadLine()

printfn "lines: %d, characters: %d" count total

The script counts the lines and characters of its input.

while not (isNull line) do

isNull tests for the null that marks the end of input. An empty line is not the end; it is returned as an empty string.

The shell's printf command writes three lines into a pipe, the second of them empty. The vertical bar connects its output to the input of our script.

λ printf 'one\n\nthree\n' | dotnet fsi count.fsx
lines: 3, characters: 8

Input as a sequence

A loop with mutable variables works, but F# collection functions are more convenient. We can turn the input into a lazy sequence of lines and process it like any other collection.

poem.txt
The fog comes
on little cat feet.

It sits looking
over harbor and city
on silent haunches
and then moves on.

This is the input file. We pass it to the script with the shell's < redirection, which connects the file to standard input.

words.fsx
open System

let lines =
    Seq.initInfinite (fun _ -> Console.ReadLine())
    |> Seq.takeWhile (isNull >> not)
    |> Seq.toList

let words =
    lines
    |> List.collect (fun l -> l.Split(' ', StringSplitOptions.RemoveEmptyEntries) |> List.ofArray)

printfn "%d lines, %d words" lines.Length words.Length
printfn "longest word: %s" (words |> List.maxBy String.length)
printfn "longest line: %s" (lines |> List.maxBy String.length)

The script reads all lines, splits them into words and prints a few statistics.

Seq.initInfinite (fun _ -> Console.ReadLine())
|> Seq.takeWhile (isNull >> not)

Seq.initInfinite calls ReadLine each time a new element is needed, and Seq.takeWhile stops at the first null. Seq.toList reads the lines once and keeps them, so the list can be used several times. A shorter way to read all input at once is stdin.ReadToEnd(), which returns one string.

λ dotnet fsi words.fsx < poem.txt
7 lines, 21 words
longest word: haunches
longest line: over harbor and city

Command line arguments

In a script, the arguments are in the fsi.CommandLineArgs array. The first element is the name of the script; the arguments written after it follow.

args.fsx
let args = fsi.CommandLineArgs

printfn "%d elements" args.Length

for i in 0 .. args.Length - 1 do
    printfn "%d: %s" i args[i]

The script prints every element of the array with its index.

let args = fsi.CommandLineArgs

fsi is an object that F# Interactive provides to scripts; it does not exist in compiled programs. Arguments are separated by spaces, and quotes keep words together, so "New York" is one argument. The shell removes the quotes before the program sees them.

λ dotnet fsi args.fsx 42 "New York" -v
4 elements
0: args.fsx
1: 42
2: New York
3: -v

Using arguments

Arguments are strings, so they are parsed like any other input. A program that cannot work with its arguments should print a usage message to the error stream and end with a non-zero exit code, which tells the shell that it failed.

sum.fsx
open System

let args = Array.tail fsi.CommandLineArgs

if args.Length = 0 then
    eprintfn "usage: dotnet fsi sum.fsx NUMBER..."
    exit 1

let parsed = args |> Array.map (fun a -> a, Double.TryParse a)
let invalid = parsed |> Array.filter (fun (_, (ok, _)) -> not ok)

if invalid.Length > 0 then
    for (a, _) in invalid do
        eprintfn "not a number: %s" a
    exit 2

let numbers = parsed |> Array.map (fun (_, (_, x)) -> x)
printfn "sum: %g, average: %g" (Array.sum numbers) (Array.average numbers)

The script adds up the numbers given as arguments.

let args = Array.tail fsi.CommandLineArgs

Array.tail drops the script name, so args holds only the real arguments.

eprintfn "usage: dotnet fsi sum.fsx NUMBER..."
exit 1

eprintfn writes to standard error, so the message is not mixed into output that another program reads. exit ends the script with the given code. The shell keeps the exit code of the last command in the $? variable; 0 means success.

λ dotnet fsi sum.fsx 4 8 15 16 23 42
sum: 108, average: 18
λ dotnet fsi sum.fsx; echo "exit code: $?"
usage: dotnet fsi sum.fsx NUMBER...
exit code: 1
λ dotnet fsi sum.fsx 3 x 5 y; echo "exit code: $?"
not a number: x
not a number: y
exit code: 2

Options

Many programs accept options such as --upper or --repeat 3 next to ordinary arguments. Names that F# Interactive uses for its own options should be avoided in scripts: with --times, for example, fsi would pass the option to the script and also print its own timing statistics. A list pattern with a recursive function takes them apart one by one and collects the settings in a record.

shout.fsx
type Settings = { Upper: bool; Repeat: int; Words: string list }

let rec parse settings args =
    match args with
    | [] -> Ok settings
    | "--upper" :: rest -> parse { settings with Upper = true } rest
    | "--repeat" :: n :: rest ->
        match System.Int32.TryParse n with
        | true, t when t > 0 -> parse { settings with Repeat = t } rest
        | _ -> Error $"--repeat needs a positive number, got '{n}'"
    | opt :: _ when opt.StartsWith "--" -> Error $"unknown option {opt}"
    | word :: rest -> parse { settings with Words = settings.Words @ [ word ] } rest

let defaults = { Upper = false; Repeat = 1; Words = [] }

match parse defaults (List.tail (List.ofArray fsi.CommandLineArgs)) with
| Ok s ->
    let text = String.concat " " s.Words
    let text = if s.Upper then text.ToUpper() else text
    for _ in 1 .. s.Repeat do
        printfn "%s" text
| Error msg ->
    eprintfn "error: %s" msg
    exit 1

The script prints its words, optionally in upper case and several times.

| "--repeat" :: n :: rest ->

The pattern matches the option together with the value that follows it. Options may come in any order and between the words. The parser returns a Result, so an invalid option produces an error message instead of a crash. For programs with many options, a library such as Argu generates the parser from a discriminated union.

λ dotnet fsi shout.fsx good --upper morning
GOOD MORNING
λ dotnet fsi shout.fsx --repeat 2 see you
see you
see you
λ dotnet fsi shout.fsx --repeat two see you
error: --repeat needs a positive number, got 'two'

Environment variables

Environment variables hold settings that apply to every program started from a shell, such as the user's home directory. A program reads them with Environment.GetEnvironmentVariable, which returns null for a variable that is not set.

env.fsx
open System

let getOr fallback (name: string) =
    match Environment.GetEnvironmentVariable name with
    | null | "" -> fallback
    | value -> value

let greeting = getOr "Hello there" "GREETING"
let width = getOr "20" "WIDTH" |> int

printfn "%s" greeting
printfn "%s" (String('-', width))

The script takes a greeting and a line width from the environment and falls back to defaults.

| null | "" -> fallback

A variable that is unset and one that is set to an empty string are both treated as missing. In the shell, a variable can be set for a single command by writing it before the command.

λ dotnet fsi env.fsx
Hello there
--------------------
λ GREETING="Good evening" WIDTH=12 dotnet fsi env.fsx
Good evening
------------

The EntryPoint function

A compiled program has no fsi object. Instead, the last file of a project may contain a function marked with [<EntryPoint>]. It receives the arguments as a string array, without the program name, and returns the exit code. Projects are introduced in Introduction to F#.

Program.fs
open System

[<EntryPoint>]
let main argv =
    match argv |> Array.map Int32.TryParse with
    | [| (true, w); (true, h) |] ->
        printfn "%d x %d = %d" w h (w * h)
        0
    | _ ->
        eprintfn "usage: rect WIDTH HEIGHT"
        1

The program prints the area of a rectangle given its two sides.

| [| (true, w); (true, h) |] ->

An array pattern checks that there are exactly two arguments and that both were parsed. The value of the matching branch, 0 or 1, is the exit code.

rect.fsproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="Program.fs" />
  </ItemGroup>

</Project>

This is the project file. With dotnet run, the arguments for the program come after a double dash, so that dotnet does not take them as its own options.

λ dotnet run -- 12 7
12 x 7 = 84
λ dotnet run -- 12; echo "exit code: $?"
usage: rect WIDTH HEIGHT
exit code: 1

A text statistics tool

The last program puts the pieces together. It reads text from standard input, takes the number of words to report from an option, and prints the most frequent words.

topwords.fsx
open System

let usage () =
    eprintfn "usage: dotnet fsi topwords.fsx [--top N] < FILE"
    exit 1

let top =
    match List.tail (List.ofArray fsi.CommandLineArgs) with
    | [] -> 3
    | [ "--top"; n ] ->
        match Int32.TryParse n with
        | true, n when n > 0 -> n
        | _ -> usage ()
    | _ -> usage ()

let text = stdin.ReadToEnd()

let words =
    text.ToLower().Split([| ' '; '\n'; '.'; ',' |], StringSplitOptions.RemoveEmptyEntries)

printfn "%d words, %d distinct" words.Length (words |> Array.distinct |> Array.length)

words
|> Array.countBy id
|> Array.sortBy (fun (w, n) -> -n, w)
|> Array.truncate top
|> Array.iter (fun (w, n) -> printfn "%-6s %d" w n)

The program counts how often each word occurs.

let text = stdin.ReadToEnd()

stdin is the F# name for Console.In. ReadToEnd returns the whole input as one string, which is the simplest choice when the input is not large.

|> Array.sortBy (fun (w, n) -> -n, w)

The words are sorted by count in descending order, and words with the same count alphabetically. usage ends the program, so the compiler accepts it in a branch that should return an int: the exit function never returns and fits any type.

λ dotnet fsi topwords.fsx < poem.txt
21 words, 18 distinct
on     3
and    2
cat    1
λ dotnet fsi topwords.fsx --top 2 < poem.txt
21 words, 18 distinct
on     3
and    2

Source

.NET API: Console.ReadLine

F# language reference: Explicit entry point

F# Interactive (dotnet) reference

In this article we have read lines and numbers with Console.ReadLine, detected the end of input, processed input as a sequence, read command line arguments in scripts, parsed options, returned exit codes, read environment variables and used the [<EntryPoint>] function of a compiled program. Parsing text is covered in F# type conversion, and reading files in F# file I/O.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all F# tutorials.