Phillip Trelford's Array

POKE 36879,255

The only 3 apps you’ll ever write…

At last week’s F# eXchange Robert Pickering gave a talk on Expression Oriented Programming with F#, with one of the slides condensing the only apps you’ll ever write down to 3:

OnlyThreeApps

In the same week fsharpWorks conducted an F# Survey, the results of which are well worth a look.

One of the questions was ‘What kind of learning material would you like to see more of?’ with a popular answer being ‘More material with short "cookbook" style information’.

So lets take a look at 2 out of 3 of the only apps you’ll ever write :)

Command line

An easy place to get started with F# is to use a popular IDE, for Windows there’s the free Visual Studio 2013 Community edition, and for Mac and Linux there’s Xamarin Studio and MonoDevelop.

To create a new console app in Visual Studio hit File –> New Project and select the F# Console Application project:

image

For the ubiquitous hello world app write:

printfn "Hello World"

Then run with Debug –> Start without Debugging (Ctrl+F5), which runs the app and waits for you to press a key.

To make things a little more exciting we could display all the files in the working directory:

let files = System.IO.Directory.GetFiles(".")
for file in files do printfn "%s" file

GUI App

An easy option in F# for creating a GUI app is to use the Windows Forms library.

To do this simply add a reference to you’re existing console application. In Visual Studio right click the project’s references folder and select the System.Windows.Forms.dll reference.

Then right click the project and select Properties to change the application type to a Windows Application:

image

Now insert the following code to display a form:

open System.Windows.Forms

[<System.STAThread>]
do let form = new Form()
   Application.Run(form)

You should see an empty window on the screen.

Let’s make things a little more interesting with a grid with some data, carrying on the file information theme:

open System.IO
open System.Windows.Forms

[<System.STAThread>]
do let form = new Form()
   let grid = new DataGridView()
   grid.Dock <- DockStyle.Fill   
   form.Controls.Add(grid)
   form.Load.Add(fun _ ->
      let files = Directory.GetFiles(".")
      grid.DataSource <- [|for file in files -> FileInfo(file)|]   
   )
   Application.Run(form)

When you run it you should see something like this:

image

That’s all folks! Just a few lines of code and we’ve got a grid up.

Summary

Hopefully you can see in this F# introduction creating a console app or GUI app is a relatively simple task.

If you’d like the complete set, then check out Tomas Petricek’s tutorial on MSDN: Creating Windows Services in F# or Mike Hadlow’s recent self-hosted web service sample: A Simple noWin F# example.

Comments (1) -

  • Phil Nash

    4/27/2015 10:13:52 AM |

    Would be a better story if creating "services" was as easy as in Erlang Smile

Comments are closed