Thursday, March 20, 2014

An adventure journey of Functional Programming and F# 2.0 in Visual Studio 2010: Part 3 of 17

Hello there!

This blog of F# contains full (long) blog posts of adventure in functional programming and F#. I call it adventure, because I’ll try to make F# as fun to as possible to learn.

NOTE:

This blog is starting to use Visual Studio from Visual Studio 2012 and Visual Studio 2013 (from Release Candidate to RTM), and provide hints of F# 3.0 in Visual Studio 2012.

Now, here are the parts:

  1. Part 1: Introduction to Functional Programming
  2. Part 2: Functional Programming Concepts
  3. Part 3: Introduction to F#
  4. Part 4: Functions, Delegates and Computation expressions in F#
  5. Part 5: F# standard libraries
  6. Part 6: OOP in F#
  7. Part 7: Using LINQ in F# (and the upcoming F# 3.0)
  8. Part 8: F# Asynchronous workflow
  9. Part 9: F# MailboxProcessor
  10. Part 10: Units of Measures
  11. Part 11: F# Power Pack
  12. Part 12: F# for Silverlight 4 (and above)
  13. Part 13: A look at F# 3.0 in VS 11 (Visual Studio 2012)
  14. Part 14: A look of Functional Programming in VB 10 and C# 4.0 compared to F#
  15. Part 15: A look of F# compared to Haskell, Scala and Scheme
  16. Part 16: F# future and what features that F# must have
  17. Part 17: Retrospective

Introduction to F#

The adventure of functional programming is still on .NET wondrous land (because this series is focusing on Visual Studio). As one of the spoken language of .NET citizens, F#, has gained quite large share over the rest of .NET languages.

I have brought you the introduction to functional programming (part 1) and also the functional programming concepts (part 2). Now, I will bring you what F# is closer, but still in a gentle deeper intro to F#.

Note: why, why we need another gentle intro to F#?

Because all of us mostly get used to the idea of imperative programming, although OOP comes along. Our mindset is full of C++, Java, VB, C#. But unfortunately, not all of us is used to the idea and the fact that C# and VB.NET are adapting functional programming style since VS 2008.

And also I often sees many of us have confused and few of us feared the F# syntax, without knowing and realizing that it’s closer to math, even it’s actually part of elementary school math!

Here’s F# logo for Visual Studio 2010:

Vis_F_blue_Lo-res 

Again, let me reintroduce you the history of F#, but now I’m putting the emphasize on F#, not the whole functional programming introduction as we already traveled there on Part 1.

F# is originated as a research project at Microsoft Research (often called MSR) in Cambridge, and it is still now. The language itself means “Fun”, not functional as many people have guessed!

The development of F# itself has been successful, it has been productized and it’s now part of first class citizen of Visual Studio programming language since Visual Studio 2010, rather than just second class by add ins.

For a research product becoming a commercial product in Microsoft (this is why it called “productization”), the product itself must undergo many process, including the preparation of these common organizational structure: program managers, senior developers, and also the “bridge” person between the research product and the developer division (often called DevDiv). Also, the vibrant community of the product has to have enough user bases, otherwise it’s not enough to justify whether the product is ready to be commercialized.

Note on F# productization:

F# itself can be considered as free, because you can still download the tool such as Visual F# for Visual Studio 2012 Express for Web. But then it must be supported, as Microsoft is also preparing a product lifecycle for it. This means somehow available as free or as commercial, being part of Visual Studio Professional, Premium, or Ultimate.

This Visual F# for web is not a template of developing ASP.NET for F#, although it install on express edition of Visual Studio Express for Web.

F# in a quick intro (also gentler)

There are 4 keywords to describe F# nicely:

  1. functional
  2. immutable
  3. succinct
  4. type inference (on local symbols and function declaration)

The functional part of F# has been described in first part and second part. Now, the remaining three of them are described here.

Immutable

F# is immutable by default. Now why I put immutable before succinct? I did this, because immutable variable (hence values) is a consequence of being a functional programming language. Also functions in functional language behaves like function in math.

Any variable (or symbol as in math) is immutable by default. In F#, this variable declaration is actually a bind to a symbol, just like in math.

Let’s revisit sample in part one:

y = x + 1

In F#, all variable and also function declaration is declared using let (almost like DIM in old BASICA and GW-BASIC before VB.NET). Therefore the above sample will be written like this in F#:

let y = x + 1

But before that, x must be declared first. You can fill x with any values.

fsbook_p3_immutable01_30DDAF36

Now, try to change the value of y by adding new declaration of it. You’ll get error warning like this:

fsbook_p3_immutable02_3A5E1FBF

It says: “error FS0037: Duplicate definition of value ‘y’ ”. This means you can’t declare more than once.

Yes, you may ask that the sample is not clear. But the main reason is, once you declared a symbol, you can’t change it again, anywhere within the scope of the variable and the function.

What if I do this?

fsbook_p3_immutable03_23C3838B

Then F# will decide that there’s a new symbol of c with a new declaration, by a known technique of shadowing. This shadowing effect behaves almost like Shadows in VB.NET, but it’s not just shadowing in inheriting object. F# can use lexical scoping just like VB, but then again the first declaration of c is shadowed by the symbol declaration of the new “c”.

Note on symbol declaration in F#:

For the rest of the part describing immutability in F#, I will use symbol as an association of symbol binding and values (assigning values to symbols and operation to symbols).

In VB, this is the shadowing sample: (using inheritance to visualize shadowing)

vb_shadowing_53812C0A

The code speaks: display() method of secondClass shadows the display() method of firstClass, and so does the display() method of thirdClass shadows the secondClass.

For more information and sample of VB shadowing, look at MSDN Library: http://msdn.microsoft.com/en-us/library/vstudio/1h3wytf6.aspx

What about immutability? If you want to have mutable values in F#, you have to declare it as mutable explicitly.

The declare a variable as mutable, we can use mutable keyword after let. Then, to modify the variable we can use “<-“ operator to denote mutability assignment

Sample:

fs_mutable_12E1704C

Do you want more sample with comparisons?

About 2 years ago I have created a Powerpoint deck when Visual Studio 2010 was in Beta 2, to illustrate this. Here’s the link: http://docs.com/ZBH

Here is the simple sample with comparison with VB and C#:

fs_immutable_slide_429F18CB

Yes, for VB and C#, immutability is not available by default. You have to declare immutability explicitly in VB and C#.

Succinct

Almost every blogs, and other websites describe F# as succinct. Why? Because the less noisier syntax nature of F# while still providing the power of static type.

Using a simple variable declaration of

let x = 6

is almost the same as

var x = 6

in C# (using C# local type inference).

But the succinctness will become more apparent when dealing with function syntaxes, declarations, and enums.

In the spirit of polyglot, let’s compare it with VB and C#:

fs_succinct_syntaxes_50FFAC5F

The code above also speaks that type in function declaration is also inferred! This brings more simpler syntax compared to VB and C#.

A multiple select case (or switch in C#) can be simplified just using pattern matching, such as these:

fs_cs_matchpattern_365831A8

While in C#:

fs_cs_switch_21D572DB

As we see, the type declaration on function parameter is not necessary! Which is now let’s look into type inferences.

Type Inferences

Again, type inference in F# is not just when declaring symbols and variables. Type inferences are also available when declaring a function’s parameters, and it also flows nicely!

Here’s a simple sample:

fs_slide_typeinfer01_2C955AE1

Just like C# local type inference, F# will decide the type accordingly. But we can also use explicit type declaration:

fs_slide_explicit_typing_0D74CEB2

Declaring type is simple, use “:” after the symbol name.

Now when type inference is used in a function declaration:

fs_slide_typeinfer02_485E922C

As we see, the function sqr is inferred differently when called! In the first body of f x:

let f x = sqr x + 1

means that the sqr x will be inferred as function that returns as integer, because it’s added to 1. The “1” is by default a whole number of Int32.

Now the second declaration of f x:

let f x = sqr x + 1.0

this will infer that “1.0” is double, therefore sqr x is a function that returns double value as the result.

This is why I called it, it flows nicely!

Now, let’s familiarize with the environment, especially the IDE. Yes, it’s Visual Studio 2010.

Using F# in Visual Studio 2010

F# in Visual Studio 2010 is available (although only in Professional and above edition, for express edition is not directly available).

After simply installing Visual Studio 2010 (Professional and above edition), this is the F# project templates: (Yes, it’s the same from part 2)

fs_projecttemplates_VS2010_3DC3557B

Yes, we can have F# for Silverlight! More on this later on part 12, F# for Silverlight 4.

The “F# Tutorial” template will get us started easily, because it provides samples to try. This includes not just simple variable and function declaration, but it also includes class, interface, and also other aspects of F# language features.

Create a project using F# Tutorial as template, and you will get a file with samples:

fs_tutorialtemplate_01307840

The tutorial in that file is available to test immediately in scripting mode.

Actually, F# can have two mode, scripting (interactive) and standard mode with debugging and compiler support.

Note on interactive:

VB and C# has interactive mode, but this isn’t released yet. This interactive tool is part of Roslyn project, it’s basically uplifting the VB and C# compiler to be more open to outside, packaged as service API.

The fun part is the interactive mode. In this mode, we can test directly the result of the F# codes, without fully compiling the whole project! As I mentioned in previous part especially Part 2, this is ideal for testing before compiling and it’s also showing a working sample of a simple REPL in action.

They way it work is easy. Turn on or activate the F# Interactive window, just highlight the row or rows of code you want to be evaluated and then press Alt + Enter keys.

If your setting of Visual Studio (the overall IDE setting) is general, you can have F# Interactive window from menu View:

fs_activate_fsinteractive_3A225EB8

This IDE setting is very important! It also changes the Visual Studio menu and also can affect the way you develop.

I highly recommend the same General Development (or simply general) setting. It will bring the same and standard layout across your team and it will make us having the same view of Visual Studio, unless you’re coding on your own with no team at all.

This setting is available from Tools –> “Import and Export Settings..”. If the menu arrangements are different, choose General Development as your preference:

fs_vs2010_ide_setting_19E2F262

Note: please ignore the Business Intelligence Settings above. This setting is only available if you install SQL Server 2012 Express (or above) with Analysis Service.

Some of you may be tempted to jump into Visual F# setting but I discourage it! Why? Because always try to have a teamwork environment, because then you will have the same perspective and the same settings across your team. This is also useful even when other team member is not using F#, instead of always sticking to his/her own choice of language.

This is also important if you want to become a true polyglot and also having a polyglot team.

Now, let’s revisit the Tutorial.fs (from the tutorial template), and highlight and test, starting from very simple sample:

fs_tutorial_interactive01_05A98A3F

to function declarations:

fs_tutorial_interactive02_6AECC858

We can directly see the signature of function f, “f : int –> int

As expected, the type inference flows nicely from simple symbol assignment to function and function result!

What about intellisense? In F#, intellisense is available, including the type signature.

Intellisense in F#

Intellisense in F# works just like C# and VB, but there are some difference.

When we are coding, pressing the dot after an object will bring the methods and the properties of the object:

fs_intellisense_01_071152CC

Now, the type inference is available, so is the intellisense.

Type inference doesn’t stop here, it can also deduce tuples. Let’s know tuples more!

 

Knowing more about tuples in F#

We already meet tuple in a quick intro in part 2, now let’s know tuples better.

Quick note: based on my previous discussion with my friends, this topic can provide quite brutal exposure to functional programming data structures. But tuples are already available in database fundamental concept, so for those who have backgrounds on computer science should be familiar. But for those in Software Engineering background like me, it’s quite challenging not just to understand it, but to share this concept with you, especially fellow software developers.

According to MSDN Library, “a tuple is a grouping of unnamed but ordered values, possibly of different types”. This simple definition was simple at first, but the word “possibly” brings multiple interpretations.

The definition should be this: “a tuple is a grouping of unnamed but ordered values that can have different types for each value”. Yes, it can have the same types for all members and it can have different types.

Declaring a tuple is simple, just like the sample from the Tutorial.fs:

let pointA = (1, 2, 3)

this means pointA is a tuple with 3 members. Because whole number is treated as Int32 (int in F#) by default, the type for each member is inferred as int.

Test this in interactive:

fs_tuple_p3_01_737CFB17

The signature will be “pointA : int * int * int = (1, 2, 3)”. Put it simple, the “*” between members means it is a “separator” between member.

fs_tuple_p3_02_5A60DF38

Yes, it can contain different types, and any numbers that has decimal point will be assumed as Double (float in F#).

You can also mix tuples with function just like swap above, and the result is interesting:

fs_tuple_p3_03_0725D0AD

Notice the single quote of ‘ in the signature. When F# encounters no type hint at all (especially when it can’t encounter literal at all), it will infer generic type on the arguments. Therefore (a, b) will be inferred as tuple that has two generic typed members.

Hence the notation is:

‘a * ‘b

instead of simple int or any other F# primitive types and non primitive. The tuple is then taken as argument of a Swap function, and then the return value is a tuple with swapped order of values. And still, the type inference flows accordingly!

For a homework practice for you all, try to do the Swap in C# or VB, and you will find why F# is truly succinct even at writing tuples.

Next journey, what do you have in store, F#? What kind of items do you have?

This spells for kind or the type of the items!

Types in F#

We have done visiting int, float, string, generics. They are not just that, F# already has many types, even before it’s implemented in .NET.

A best example of this is bigint. It is already available in F# long before .NET 4.0 has it.

The best? It is larger than Int64. Try to write bigint? Because it’s arbitrary, you can simply have 10000000000000000000000000000000000000 and goes on!

This bigint is now fully implemented in .NET 4.0, although it was available back then in .NET 2.0 Beta1 but Microsoft had decided to delay the implementation in .NET 2.0. But although it seems native/primitive in F#, bigint isn’t a primitive type.

Then, what are F# primitive types?

fs_primitivetypes_lists_4CCD3EDF

For more information, please check on the link above. Throughout this blog series and for the next submissions, I encourage you to always check MSDN Library as official documentation of Microsoft .NET and programming languages. It’s a good habit to get used to read the manual and practice first, rather than always consulting Google or Bing.

The usage of unit is not just for return value of a function that has no value, it can also be used as function signature that means that it has no parameter.

Next: more on function and delegate in F# (part 4), including quotations, including the detail of the power of pattern matching in functions!

Wait, wait… what about lazy??? Lazy evaluations are available because of the laziness evaluation, and this involves the internal work of function that returns iterator and also at runtime! Move on to part 4!


Further reference links

  1. Visual F# for Visual Studio 2012 Express for Web availability announcement, http://blogs.msdn.com/b/fsharpteam/archive/2012/09/12/announcing-the-release-of-f-tools-for-visual-studio-express-2012-for-web.aspx
  2. Download the old BASICA, GWBASIC, and also VB 1.0, http://deger.republika.pl/Download_MS_Basic_versions.htm
  3. My F# on Visual Studio 2010 Beta 2 slide on Microsoft Docs, http://docs.com/ZBH

No comments:

Post a Comment