Getting Started with F#

F# is a functional programming language, where a program is a series of bindings of expressions to identifiers. Here are some examples:

        let x = 3 + (4 * 5)
        let res = (if x = 23 then "correct" else "incorrect")

When executed this program binds "x" to the value 23 and "res" to the string "correct". You can execute this directly in "F# Interactive" (fsi.exe) as follows – note the use of ;; to separate entries given to fsi.exe:

        > bin\fsi.exe
          MSR F# Interactive, (c) Microsoft Corporation, All Rights Reserved
          F# Version ...

          > let x = 3 + (4 * 5);;

          val x : int
          
          > let res = (if x = 23 then "correct" else "incorrect");;

          val res : string

          > res;;

          val it : string = "correct"

The last interaction shows how to enter expressions into F# Interactive and have them evaluated immediately. An expression is implicitly bound to a variable called it.

F# is not a "pure" functional language, so the evaluation of expressions may have side effects, e.g., I/O, mutating state, displaying graphics, etc. Here is a simple F# console-based program:

        let x = "Hello World";;
        System.Console.WriteLine(x);;

If placed in a text file hello.fs then this program can be compiled from the command line as follows:

        > fsc hello.fs

and executed using

        > hello.exe

You may prefer to use the file extension .ml, as in hello.ml. F# code can also be placed in a library, e.g., lib.fs may contain

        let myLibFunction() = System.Console.WriteLine("Hello World")

and your hello.fs may simply contain

        let main = Lib.myLibFunction()

Here "main" is not a function but rather a dummy value to hold the result of the computation on the right of the "=" symbol. You can compile using:

        > fsc -a lib.fs
        > fsc -r lib.dll hello.fs

producing a lib.dll library and the hello.exe executable. Both of these are .NET assemblies. You can also compile your library and main program together to produce a single hello2.exe:

        > fsc -o hello2.exe lib.fs hello.fs

Typical projects will compile several F# files into each assembly.