Thursday, February 12, 2009

How I'm Learning F# - Writing the First Application

Over the past few months, I've been hearing more and more about the use of functional programming concepts and also languages like Haskell and F#.  While some of the initial musings that I've read revolved around how the concepts have been around for decades and that it makes financial and scientific applications easier to read and write, I couldn't find a good reason to start learning it for my typical line-of-business application design and development job or even some of my basic hobby projects.  Nonetheless, I kept getting drawn to the concept and have decided to focus on learning it.

This post marks the second entry of a series that I'll be writing to discuss how I'm going about learning F#.  While I'm not saying that my method of learning is ideal and should be followed by others, I'm just reporting how I'm going about doing it.  Over the course of this series, my goal is to provide other .Net developers a(nother) resource for learning the F# language as well as apply the language into some non-financial or scientific scenarios.

 

Series Table of Contents:

  1. Finding Resources
  2. Writing the First Application

 

Downloadable Resources:

 

Setting Up Visual Studio 2008 with F#:

As of this writing, F# is at CTP status since September 2008 (v1.9.6.2).  For this example, and possibly for the remainder of the series, I'll be using this September 2008 CTP of Microsoft F#.  This CTP installer only works with Visual Studio 2008.  The CTP version does not work with Visual Studio 2005 (which previous versions did) nor the Visual Studio Express editions.  If you would like to use F# using Visual Studio 2005, please refer to this StackOverflow question about how to set up F# in Visual Studio 2005 using an older version. NOTE: If you are using an older version of F# for use in Visual Studio 2005, I cannot guarantee that the examples presented in this series will work.  After you have downloaded and installed F# (either the CTP or a previous version), we are ready to begin writing our first F# application.

 

Writing the "Hello,World!":

Like many great computer books, this series will be starting with a simple example which we'll dissect afterwards.  In order to write the example, we'll need to start a new F# project in Visual Studio.  If we go to File > New Project..., we are treated to the following dialog window:

NewProjectDialog

The projects listed under Visual F# include a F# Application, a F# Library, and a F# Tutorial.  For the sake of this example, we'll be creating an F# Application named HelloWorldFSharp.  After clicking on the OK button, Visual Studio creates the new F# project containing a single Program.fs file. 

When the project is created, the Program.fs file contains a single line #light.  This tells the F# compiler to use the lightweight syntax of F# which removes some of the verbosity of the language and applies rules around white-space.  In the majority of examples on the Internet and books, the lightweight syntax is used and will be used going forward here as well.

Under the #light line, add the following code snippet:

let question = "How are you?"

let sayHello name =
    "Hello, " + name + "! " + question

In this code, we are doing two things.  First, we are declaring a variable named question.  Second, we are declaring a method called sayHello and takes a parameter called name. The sayHello method concatenates some strings together and returns the composed string. When using the #light syntax, every indented line is considered part of the function or action with the last line being the return value.

One thing to mention about F# when compared to other languages is that variables are immutable.  Once a variable is declared (and given a value), that value can never change.  I believe there are some exceptions to this when interacting with object properties; however, at the core of the language, basic variables cannot be re-declared nor their values redefined after they have been initially declared. Because of this, many F# documents and tutorials will use "values" instead of "variables" to prevent the confusion.  I'll attempt to follow this pattern.

 

One thing that a developer coming from VB.net or C# may notice is that there are no types defined here.  F# infers typing based on the value and how they are used.  If we wanted to declare a type for our question and name values, the code would like like the following:

let (question : string) = "How are you?"

let sayHello (name : string) =
    "Hello, " + name + "! " + question

In F#, you can declare the type by using (variablename : type) syntax.

 

Now that we've seen how to declare a value and a method, we can output a value to a console window using the following line:

printfn "%s " (sayHello "James")

Here, we are using the printfn method which prints formatted text to the console window.  The %s is a placeholder for a string value which we are supplying by calling our sayHello method passing in the name "James". In this example, we're treating the method like a value.

 

Here is the full code of Program.fs.

   1: #light
   2:  
   3: let question = "How are you?"
   4:  
   5: let sayHello name = 
   6:     "Hello, " + name + "! " + question
   7:  
   8: printfn "%s " (sayHello "James")

 

Running the Program using F# Interactive:

At this point, we can either go the Build menu and build the project like many other console applications or we can use a feature unique to F# called the F# Interactive window.  F# Interactive (fsi.exe) allows you to run sections of your F# program as well as write ad-hoc F# statements.  To use F# Interactive from within Visual Studio, highlight the code you wish to run and press Alt+Enter.  A new Visual Studio panel opens for F# Interactive and reports information about the code (or the error it generates).

For example, if you were to highlight the line where we declare our value question and press Alt+Enter, the following will appear:

val question : string

What this line explains is that we have a value called question that is of type string. If we do the same to our sayHello method, the following appears:

val sayHello : string -> string

This line states that sayHello is a value that accepts a parameter of type string and returns (signified by the -> ) a value of type string.  If we highlight the all of the code we've written so far, we are shown the following:

val question : string
val sayHello : string -> string

Hello, James! How are you?

This shows us the same output as we had previously for question and sayHello.  In addition, it executes the last line and displays the output.

 

Conclusion:

While this wasn't the largest demo nor the most unique, it is a simple step forward.  The premises of immutable variables (values) being declared and understanding the lightweight syntax are important to learning F#.  Over the next post of the series I'll be making some different applications in order to continue to explore F#'s syntax and it's power.  F# can do pretty much everything that VB.net or C# can do (with a few exceptions I'm now finding out) and hopefully the next posts will help us begin to find examples of where to apply it.


kick it on DotNetKicks.comShout it

4 comments:

  1. I have worked in .NET projects for some time (about a year) and I switched my focus to functional languages. Also, my CS studies provided me with heavy background on functional languages (SML, OCaml, etc..).

    I red your post and two things lighted up.

    First of all.
    In functional languages there is no concept of VARIABLE. VARIABLES do not exist beacuase assigning values to them carries SIDE-EFFECTS.

    Second thing you mislabeld function with method.
    It may seem like a little thing now, but when you go through partial application concept of function becomes important.

    Nevertheless, great idea.
    In next part you could show the big .NET community beaty of functional languages. Stun them with quicksort, perhaps some tree definitions or so on, so on.

    If you like, I can provide you with some basic project euler solution in Haskell, if you need code samples.

    ReplyDelete
  2. @Hegi

    Thanks for the feedback. I'm approaching F# after years of experience with Perl, Java, VB(5, 6 and .net), and C#. Because of my background, I'm looking at attempting to draw parallels between F# and functional programming and the languages I already know.

    By taking this stance, I'm working on using such parallels to explain on the pieces of this basic syntax. That's the reason why I started with "variable" but then began using "value" after I explained the difference. In the languages I already know, Function, Method, Subroutine, etc. are all interchangeable in most senses and is the reason why I said method instead of Function. Going forward I will focus on using the correct terminology though.

    As far as showing the beauties of functional languages, I'm still learning about such and am not to the point, yet, to fully grasp and appreciate such. As I get deeper into the language, I'm certain I'll be seeing such; however, for right now, I'm just focusing on learning the language and leveraging it to make programs in general. I'm sure after the next couple of posts that I have planned, I'll be considerably more competent where functional languages excel at and where they can be applied.

    Lastly, I have seen and worked on some euler problems using F# and I do not plan on using them in any of my posts (though that stance is subject to change of course). My reasoning for such is that there are many other resources for euler problems and very few of them map to line-of-business applications that many developers use. I'm wanting to focus on (first) an understanding of the language and (second) how it can effectively be applied to the types of development that I and many of my colleagues do.

    Again, thank you for your feedback and I'll be considering it as I continue to write my future F# posts.

    ReplyDelete
  3. "F# can do pretty much everything that VB.net or C# can do (with a few exceptions I'm now finding out) "

    What do you mean with the "with a few exceptions Im now finding out" ?

    ReplyDelete
  4. There are some additional resources for learning F# at http://fsharp4u.com.

    ReplyDelete