Wednesday, 30 March 2016

Getting started with writing F# code

In previous post we looked at the high level overview of Function programming language and introduction to F#. In this post we will start with basic things to learn Visual F#.

ToolVisual studio 2013

We’ll start with a console application. Launch the visual studio and Add a new F# console application.

Let’s name it “FSharp.Starters.Console”

Open the Program.fs file in editor and let’s write something in it. You’ll see an entry point method something like below:

// Learn more about F# at http://fsharp.net

// See the 'F# Tutorial' project for more help.

 

[<EntryPoint>]

let main argv =

    printfn "%A" argv

    0 // return an integer exit code

Let’ s change it to write something on console.

let SayHello() = printfn("Hello World!!")

 

[<EntryPoint>]

let main argv =

    SayHello()

    System.Console.ReadKey() |> ignore

    0 // return an integer exit code

So we have defined our very first function ‘SayHello()` which takes no argument and print simple “Hello World!!”. Now to run it simply press F5.



There are two ways you can run and test this F# code. Either via console application or using F# interactive windows. You can open the F# interactive windows in Visual studio from menu View -> OtherWindows -> F# Interactive.

Now you can go to Program.fs and select all code and press Alt + Enter to run the code in interactive window. If this doesn’t work then you can select all and right click in code editor and select “Execute in Interactive”

This will interpret the code in the interactive code and you’ll see the output like below:

val SayHello : unit -> unit

val main : argv:string [] -> int 

> 

Now the method ‘SayHello’ is ready to run. To invoke any method in Interactive we run it by typing method name and ending it with double semi colon e.g. “MethodName() ;;”. So let’s run the above code right away:

> SayHello();;

Hello World!!

val it : unit = ()

Congratulations! You now know how to run any Fsharp program/script. Let’s go ahead and put some arguments in the SayHello() method. To declare method argument is simple, just write the next to the method name like below:

let Greet To =

    if System.String.IsNullOrWhiteSpace(To) then

       "whoever you are"

    else

        To

 

let SayHello() To =

    printfn "Hi, %s" (Greet To)

Important Note: Next statement or method definition is identified by 4 spaces or single Tab in visual studio. Because there are not block defining like curly braces in C#. So it’s all defined via indentation.

E.g. Below statement would print “inside the if..” and return value “who ever you are”. The last statement in the same indentation is returned value.

    if System.String.IsNullOrWhiteSpace(To) then

       printfn("inside the if..")

       "whoever you are"

 

Take below example – The if statement would only print “inside the if..” the return value is out of if block.

    if System.String.IsNullOrWhiteSpace(To) then

       printfn("inside the if..")

    "whoever you are"

Now let’s run it interactive window. Select the these methods and right click in editor to choose “Execute in Interactive”.

val Greet : To:string -> string

val SayHello : unit -> To:string -> unit

val main : argv:string [] -> int

.. And with default or empty value:

> SayHello() "";;

Hi, whoever you are

val it : unit = ()

Hope you’re getting more confident, now let’s do something more like writing an algorithm to print nth Element of Fibonacci series. We’ll be using recursion to find the value. In F# the recursion is achieved via specifying a special keyword ‘rec’ with function. If you don’t specify the ‘rec’ word you’ll get the error while trying to achieve recursion.

let rec fib n =

    if n < 2 then

       n

    else

       fib (n - 1) + fib (n-2)

 

let find() n =

    printfn "%d" (fib n)

Now let’s run it:

val fib : n:int -> int

val find : unit -> n:int -> unit

> find() 10;;

55

What we learned in this post:

  1. Writing a basic function and running in console application.
  2. Running program in Interactive window.
  3. Using Managed library method in F# code.
  4. Using If..else.
  5. Methods with arguments.
  6. A basic recursion program.

To learn more about F# keywords, Symbols and literals follow below links: