|
F# Manual
- Contents
Let's write a program in a file main.fs, e.g. printf "Hello world" and the compile and run it using fsc.exe: > "c:\Program Files\fsharp-1.9.4.19\bin\fsc" main.fs > .\main Hello world Fair enough. Noew enter it into fsi.exe: C:\fsharp> bin\fsi MSR F# Interactive, (c) Microsoft Corporation, All Rights Reserved F# Version 1.9.4.19, compiling for .NET Framework Version v2.0.50727 > printf "Hello world\n";; Hello world > open System.Windows.Forms;; > let f = new Form();; val f : Form > f.Visible <- true;; > f.TopMost <- true;; > f.Text <- "Welcome to F#";; > let rb = new RichTextBox();; val rb : RichTextBox > f.Controls.Add(rb);; > rb.Dock <- DockStyle.Fill;; > rb.Text <- any_to_string ("Hello","World");; > > #q;; Note the ";;" to terminate entries into fsi.exe. If using F# Interactive from inside Visual Studio these entries are added automatically when you send across text using Alt-Enter, and in conjunction with the experimental 'hardwhite' syntax you won't need to use ;; at all. Now let's write it another way: do List.iter (fun s -> print_string s) ["Hello"; " "; "world"] do print_newline() That shows you how to use function values (lambdas) and one function from the list library (nb. do is much the same as let _ = ). List processing is very common and powerful in functional programming. Of course we get the expected result when we run the above program. Here's still another way, which shows you how to define and use new record and class types with properties and constructors : type Data = { first: string; second: string; } type MyDataWrapper = class val data : Data new(data) = { data = data } member x.First = x.data.first member x.Second = x.data.second end let myData = new MyDataWrapper({ first="Hello"; second="world"; });; printf "%s %s\n" myData.First myData.Second;; (Note: of course you could do this all with just one class with two val fields, but then again you could do the whole program in one line :-)) And here's another way, which shows you that you can call the .NET standard libraries directly instead of the additional libraries provided with F#: System.Console.WriteLine("Hello world");; Finally, to write components you will often want to write signature files (.fsi). Here's a very simple interface file: val double: int -> int val four: int and an implementation for it: let double x = x + x let four = double (double 1);; printf "four = %d" four |