Monday, May 12, 2014

An adventure journey of Functional Programming and F# 2.0 in Visual Studio 2010: Part 5 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

F# standard libraries

Just like .NET base class libraries (often called .NET BCL), F# has its own standard libraries especially to create immutable collections including immutable generic lists. The libraries include operations such as map, filter, fold, unfold, and many more.

Begin with this chapter, all of the technical explanation will be mostly based on MSDN Library of VS 2010 SP1 and VS 2012.

Overview of local help documentation in VS 2010 and VS 2012

Using MSDN Library documentation, the standard libraries is named as F# core libraries under Visual F# documentation.

This is on MSDN help viewer of VS 2010: (after installing VS 2010 SP 1)

help_vs2010sp1_13E78452

NOTE: I recommend installing VS 2010 SP 1. There are many worthy features to consider, such as the return of non-browser help viewer (alias Help Viewer 1.1), bug fixes, stability and performance improvement.

If you use VS 2012 (formerly VS 11) the Help viewer will be:

help_vs2012_211DE798

The content of those two is almost similar, but the organization of contents are different. Of course, VS 2012 content is newer.

Getting started section in VS 2010 is available:

help_vs2010sp1_fsharp_48848E35

Getting started is gone in VS 2012 MSDN help, but it’s essentially the same in the section of “Using Visual Studio to write F# programs” like below:

help_vs2012_fsharp01_62784E57

The standard library of this part focuses on F# 3.0 on Visual Studio 2012.

The namespaces are: (with description from MSDN)

  • Microsoft.FSharp.Collections Namespace (F#): describes the F# collection namespace, including arrays, lists, maps, sequences and sets.
  • Microsoft.FSharp.Control Namespace (F#): describes the F# control namespace, including support for asynchronous programming, message passing, and event-driven programming.
  • Microsoft.FSharp.Core Namespace (F#): describes the F# core namespace, including core operators, attributes, and types.
  • Microsoft.FSharp.Core.CompilerServices Namespace (F#): describes internal libraries used by the F# compiler.
  • Microsoft.FSharp.Data Namespace (F#): describes the F# data namespace, which contains type providers for data access, as well as units of measure.
  • Microsoft.FSharp.Linq Namespace (F#): describes the F# Linq namespace, which includes types that support F# query expressions.
  • Microsoft.FSharp.NativeInterop Namespace (F#): describes library support for F# native interoperability.
  • Microsoft.FSharp.Quotations Namespace (F#): describes the F# quotations library.
  • Microsoft.FSharp.Reflection Namespace (F#): describes the F# reflection API, which extends .NET reflection to support F# types.

Those namespaces are very important, especially the Microsoft.FSharp.Core.

The Microsoft.FSharp.Linq focuses on LINQ on F#, which will be described in detail in part 7, Using LINQ in F#.

The Microsoft.FSharp.Data contains type providers and units of measure. Units of measure will be described in detail in Part 10, the data and type provider will be described in Part 13.

F# Collections in Microsoft.FSharp.Collections

The F# collections are all derived from IEnumerable and IEnumerable(Of T), just like those collections in .NET Base Class Library, But F# offer this trait: it’s immutable by default.

In F#, there are type definitions (the ones in MSDN Library and the type definition) and type abbreviations. Type abbreviations are types that function as aliases for types.

For example: seq<’T> in F# is type abbreviations for IEnumerable(Of T) (or IEnumerable<T> in C#). This makes coding more convenient, but you have to be sure that your type abbreviation are consistent and understandable by the rest of your software development team or your library user.

Type abbreviations in F#

Type abbreviations in F# can be declared using this syntax:

type type-abbreviation = type-name

For example, the type definition of seq in F# is:

type seq<'T> = System.Collections.Generic.IEnumerable<'T>

A word of caution, there is this restriction about type abbreviations in MSDN Library:

Type abbreviations are not preserved in the .NET Framework MSIL code. Therefore, when you use an F# assembly from another .NET Framework language, you must use the underlying type name for a type abbreviation.

For more details on type abbreviations, visit MSDN LIbrary: http://msdn.microsoft.com/en-us/library/dd233246.aspx

Let’s get back to F# collections. I can describe F# collections with the references from MSDN Library, but that is available for all of you, my dear blog readers, to read and to try.

Looking at F# Collection description from MSDN, this is a table to describe F# collection:

fsharp_collections_2FE4CB18

Table (preformatted) above taken from: http://msdn.microsoft.com/en-us/library/hh967652.aspx

What about the corresponding type in .NET? To further quickly understand collections of F#, here is the comparable classes in .NET Base Class Libraries (BCL):

type_abbreviations_netbcl_equivalent_2F0C652E

Map in F# can be compared with Dictionary<Key,Value> in .NET BCL but with added twist: it’s immutable in F#.

As noted above, an equivalent F# counterpart of List<T> in .NET BCL is ResizeArray<’T>, not list<’T> in F#.

A list in F# is an immutable single linked list, meaning that once you set the value you can’t modify it anymore. Do not confuse F#’s list<’T> with .NET List<T>!

Any operations on collections are defined in modules.

For example, map and filter operation of seq is defined in Seq module.

These are the list of modules in Microsoft.FSharp.Collections:

fsharp_modules_collections_6672765C

This part/chapter will not describe all of the module, as it only focuses on the most and widely used: Seq and List.

Seq module

Seq module contains mostly operations that has overall similar functionality with System.Linq.Enumerable but this feature has difference in the parameter. Seq module use F# delegate (in the form of FastFunc) with currying and higher-order function supports, rather than common Func delegate.

Common operations in Seq will be explained with Enumerable counterparts if available.

Creating sequences

Creating sequences in F# has these ways:

  1. create sequence expression
  2. using Seq.empty
  3. using Seq.singleton
  4. using Seq.Init
  5. using Seq.ofArray (create sequence from array)
  6. using Seq.cast to cast any IEnumerable to sequence
  7. create infinite sequence

Sequence expressions in F# is:

A sequence expression is an expression that evaluates to a sequence.

This can be confusing, but a sequence expression is simply a sequence to create a “seq” with a sequence of values.

Samples:

seq { 0 .. 20 }

It will create a sequence of 0 to 20.

Sequence with increments can also be created, like this sample:

// Sequence that has an increment.
seq { 0 .. 10 .. 100 }

It will create a sequence of 0 to 100 with increment of 10.

We can also create sequence by using more expressive for loop.

Simple for loop in sequence expression sample:

seq { for i in 1 .. 10 do yield i * i }

The yield can be replaced with “->” operator so “do” can be omitted, like this:

seq { for i in 1 .. 10 -> i * i }

There are also many samples to use from MSDN Library.

The following code uses yield to create a multiplication table that consists of tuples of three elements, each consisting of two factors and the product.

fsharp_seq_multipleyields_0DA7E31B

You can create empty sequence using Seq.empty.

The sequence created by Seq.empty can be created with generic type or by using concrete type parameter.

Sample:

let emptySeq = Seq.empty
let emptySeqString = Seq.empty<string>

We can check the type using F# interactive to proof the resulting generic sequence, like the below screenshot:

fsharp_emptysequence_6B03A49F

Now, we are going to create sequence using Seq.singleton. The purpose of Seq.singleton is simple: we want to create a sequence that only has one element.

Sample:

let seqOne = Seq.singleton 10

Using Seq.Init is simple. Seq.init will create sequence using function expression, therefore give you more expressive power, not just using for in a sequence expression before.

The sample is:

let seqFirst5MultiplesOf10 = Seq.init 5 (fun n -> n * 10)
Seq.iter (fun elem -> printf "%d " elem) seqFirst5MultiplesOf10

The result will be:

0 10 20 30 40

This is the screenshot:

fsharp_seq_init_3D29CBF2

To create sequence from an array, use Seq.ofArray from an array, or you can use pipeline.

// Convert an array to a sequence by using Seq.ofArray.
let seqFromArray2 = [| 1 .. 10 |] |> Seq.ofArray

Creating a sequence from existing IEnumerable is possible by using Seq.cast.

The signature of Seq.cast is: (from http://msdn.microsoft.com/en-us/library/ee370344.aspx)

Seq.cast : IEnumerable -> seq<'T>

A sample of Seq.cast to create sequence ftom weakly typed ArrayList:

let mutable arrayList1 = new System.Collections.ArrayList(10)
for i in 1 .. 10 do arrayList1.Add(10) |> ignore
let seqCast : seq<int> = Seq.cast arrayList1

To create infinite sequence, you can create infinite sequence by using Seq.initInfinite.

According to MSDN LIbrary, this is the explanation from Sequence page:

For such a sequence, you provide a function that generates each element from the index of the element. Infinite sequences are possible because of lazy evaluation; elements are created as needed by calling the function that you specify. The following code example produces an infinite sequence of floating point numbers, in this case the alternating series of reciprocals of squares of successive integers.

The best way to understand this is by looking at the sample:

fsharp_seq_initinfinite_136650FF

Sequence operations

Other operation of Sequence is: (with the corresponding LINQ’s Enumerable equality)

  • Seq.average (the concept is equal to Enumerable.Average with no parameter
  • Seq.averageby (the concept is equal to Enumerable.Average with delegate as parameter)
  • Seq.pairwise
  • Seq.windowed
  • Seq.map (the concept is equal to Enumerable.Select)
  • Seq.filter (the concept is equal to Enumerable.Where)
  • Seq.iter
  • Seq.iteri
  • Seq.sort
  • Seq.sortby (the concept is equal to Enumerable.OrderBy)
  • Seq.groupby (the concept is equal to Enumerable.GroupBy)
  • Seq.fold
  • Seq.unfold (the opposite conceptual of Seq.fold)
  • Seq.distinct (the concept is equal to Enumerable.Distinct)
  • Seq.reduce
  • Seq.scan
  • Seq.sum (the concept is equal to Enumerable.Sum with no parameter)
  • Seq.sumby (the concept is equal to Enumerable.Sum with delegate as parameter)

Those are commons operations of Seq modules, as in F# 3.0 in Visual Studio 2012, and it’s the same in F# 2.0 (in Visual Studio 2010). Future version of F# may have additional features or functionalities.

Seq.pairwise has interesting operation:

Returns a sequence of each element in the input sequence and its predecessor, with the exception of the first element which is only returned as the predecessor of the second element.

But simply the result of Seq.pairwise is a tuple with 2 element that defines pairs.

To understand it well, see Seq.pairwise in action:

fsharp_seq_pairwise_77751C06

Seq.pairwise and Seq.windowed has the same transformation result, but Seq.windowed produces an array of paired elements.

Seq.iter, Seq.iter2 and Seq.iteri will enumerate a sequence and do something for every iteration, this is why it named with “iter”. Consider it’s the same as “for each” in C# and VB but with functional approach.

Seq.iteri is a special case, it will give information of the current index of the sequence as parameter for the operation (both Seq.iter and Seq.iteri will need function to perform operations).

This iteration is simply encapsulating side effects as it has no relation on changing the member or element value of the sequence.

Sample of Seq.iter:

printf "Seq.iter: "
Seq.iter (fun (a,b) -> printf "(%d, %d) " a b) (seq { for i in 1..5 -> (i, i*i) })

There’s no equal implementation of Seq.iter, Seq.iter2 and Seq.iteri in  .NET BCL, but you can create it easily on your own with delegates.

List module

This section is not just describing List module in F#, but this section will also provide basic list in F# conceptually.

A list in F# is an ordered immutable list of element with the same type. A list has index, therefore enumerating a list can go forward and backward or simply going to a specified location by using index.

Creating lists

You can define a list by explicitly listing out the elements, separated by semicolons and enclosed in square brackets, as shown in the following line of code:

let list123 = [ 1; 2; 3 ]

Declaring the value of a list must be enclosed in “[..]” pair. This is different when defining array in F#, an array has to be enclosed in “[| … |]”.

Not just in a single line, you can also put line breaks between elements, in which case the semicolons are optional. The latter syntax can result in more readable code when the element initialization expressions are longer, or when you want to include a comment for each element.

Sample:

fsharp_alternative_list_syntax_1B4DCD94

You can also create F# list with type mentioned explicitly and also the element can contain the same type of objects or derived objects.

Sample:

let myControlList : Control list = [ new Button(); new CheckBox() ]

Unfortunately, F# does not support covariance and contravariance like those in C# and  VB, although .NET CLR supports it as well.

You can also create List in sequence expressions just like in creating sequence.

Sample:

let squaresList = [ for i in 1 .. 10 -> i * i ]

Again, all list in F# is immutable.

Operators for working with Lists

Lists can be concatenated as long as the types are the same by using the "@" operator, for example:

let list3 = list1 @ list2

You can attach elements to a list using :: (cons) operator. Again, the elements type has to be the same.

For example:

let list2 = 100 :: list1

List properties

These are common properties of a List:

fsharp_common_listproperty_41437DEA

List in F# can be used and accessed using List properties of Head and Tail, in the form of pattern matching.

For example below, the code will recursively sum the head with the rest of the elements:

fsharp_list_recursive_23EE2620

You can also iterate a list with index and do additional side effects with List.iteri.

Operations in List are essentially the same as in Seq modules.

Overview of Microsoft.Fsharp.Core and Microsoft.Fsharp.Core.CompilerServices

Basically, these namespaces are the core of F# language infrastructure.

This namespace of Microsoft.Fsharp.Core contains functionalities, including language primitives, operators, attributes, primitive types, strings, and formatted I/O.

These are the modules in Microsoft.Fsharp.Core with the explanations:

image_77D1292E

The equivalent class for Printf module in .NET BCL is Console, with the exception of bprintf that print to StringBuilder.

The format of the string format to be used as output is not the same as formatting in Console, because the syntax is different.

Sample printf:

printf “Hello world”

With format:

printf “number is %d” 5

This is the list of formats:

fsharp_printf_format_46823ECE

Microsoft.Fsharp.Core.CompilerServices contains some internal functions for use by the F# compiler, and also types for implementing type providers.


Further reading

  1. MSDN Library on Sequence: http://msdn.microsoft.com/en-us/library/dd233209.aspx
  2. MSDN Library on F# standard library: http://msdn.microsoft.com/en-us/library/ee353567.aspx

Friday, April 4, 2014

The whole language, base library, tooling of F# is open source

Yes, my blog audiences! You read it right!

Just visit the starting repo in codeplex: http://visualfsharp.codeplex.com/

Capture_official_fsharp_codeplex_27128231

And don’t worry, this F# repo in codeplex is legit, it’s maintained by F# developers at Microsoft.

So now we can involve directly in the future direction of F# language (including F# compiler), library, tooling in Visual Studio!

Note: in this repo, it’s advised to use Visual Studio at least Visual Studio 2012 to compile F# language repo, tooling and libraries.

Can’t wait to contribute to F# codeplex! Yayyy!

Wednesday, April 2, 2014

An adventure journey of Functional Programming and F# 2.0 in Visual Studio 2010: Part 4 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# (you are here)
  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

Function, Delegates and Computation Workflow in F#

Before we dive deeper into this, please remember one thing: functional programming is programming with functions, just like mathematical functions. It doesn’t matter whether we are into pure functional or non pure functional.

Pure functional or non pure programming has to be able to handle side effects, and this is why Monad concept is so popular in functional programming languages. Therefore it’s useful to know Monad concept as well.

We are now learning the what the heart of functional programming is, the function. Only now let’s dive and focus on F#’s functions.

Functions in F#

In functional programming, there are no differences between data and functions, and functions can be passed as data. We already can pass function as arguments using delegates. But functions and delegates in F# are quite different from C# and VB delegates that usually uses Func<T>, Func <T,TResult> and the other larger amounts of Func parameters.

We have learned that in previous part 2 and part 3, functions in F# are special. They can be curried and then can be chained and also composed as higher order function, not just simple function that return a value.

The function itself can be treated as data, therefore can be passed as parameter to other function.

We already have this in .NET, under the name of Delegate. Because it’s on .NET, it’s available for other languages not just F#; delegates can be immediately used in C#, VB and managed C++.

Let’s make a function that has square operation:

let square x = x * x

The signature will be:

int –> int

Because there’s no type declared, the default will be Int32.

Now, using the function is simply calling the function with parameter, like this example:

square(5)

Of course the result is 5 x 5 = 25.

In F#, a function is curried (see previous part 2) and you will be able to chain it up and to create a higher order function.

Why do you have to care about the signature? Because this is the nature of F# function: it can be curried as well just like functions in part 2. Also it’s different from VB and C# when it has been compiled!

Before diving deeper, let’s dissect common F# code in a project (instead of using interactive mode).

By default, the common function declarations of F# exists in Modules, and these modules are simply the same as static classes in C# and Modules in VB. But declaring functions in F# is different.

Here is a sample of math module:

module MathModules

let sqr x = x * x

let rec simpleFactorial x =
if x = 0 then 1 else x * simpleFactorial x - 1

As we see, it’s simple.

Now, let’s dive into the source code of MathModules in C#: (using free JustDecompile from Telerik)

MathModules_Decompiled_4BC1F8CC

In the source in C# we can see that it has CompilationMapping attribute attached to it, and it’s simply to define the class as Module in F#. Without any modifier means that all functions in F# are public and static by default.

Again, the source decompiled in C# is longer than the one in F#, and it has many noises.

As described in previous parts (especially part 2 and part 3) if there’s no type signature in a simple arithmetic operation, the type will be inferred as integer.

What about multiple parameters?

fs_multipleparam_402C3B8D

Then the decompiled version will be:

MathModules_v2_Decompiled_241B7CA2

Again, it’s different, and there is CompilationArgumentCounts attribute at the multiply function.

What is this attribute, really? Seeing this on MSD Library:

CompilationArgumentCounts_MSDN_library_519C9C65

It means that this function accepts a partial application of some of its arguments. Now, when we have multiple parameter, then it can be curried as well!

Let’s recall this currying sample from Part 2:

fs_sample_curried_1BD335C8

Now, let’s incorporate those sample into our MathModules:

fs_multipleparam_curried_6CA14A30

Now we have a higher-order function, it is “makeFactorOf3”.

And launch a decompiler tool to sneak in C#: (I have hidden the same sqr method to increase overall source code difference)

MathModules_v3_Decompiled_713754EA

F# compiler has converted makeFactorOf3 to be typed as FSharpFunc<int,int>!

And the F# compiler generates new internal class of makeFactorOf3u004012 with code that has invocation of multiply. This is where the similarity between F# and other languages in Visual Studio break!

And you might wonder how to call this function from other languages such as C# and VB? Later on Part 14.

Now let’s explore F# functions and delegates deeper.


Returning value of function result


By looking at simpleFactorial function, we can have function body more than one line and also can have statements. But there’s one convention: the final line on the function body or the entire expression within the function body (including the statement) must evaluate into a value, and this value is the return value (or simply the result) of the function. Therefore, there’s no verbose return statement in F#.

But we must include indentation to signify that the function is indeed having many statements inside for functions that has many statements.

This concept will imply that we must evaluate value returned in a maintainable manner, as simple as possible!

This is different from C# and Visual Basic which can have return statement at any position! But this simple convention will give us more discipline that always has one point of return value, instead of having many return statement in our code.

What about using match (pattern matching) in F#? It is still evaluate to a value to be immediately returned as function result.

See this sample:

let defineQuality grade = match grade with
| "A" -> "Best"
| "B" -> "Very good"
| "C" -> "Good"
| "D" -> "Bad"
| _ -> "Undefined"

Compare it to C# code with the same functionality:

        String defineQuality(String grade)
{
var qual = "";
switch (grade)
{
case "A":
{
qual = "Best"; break;
}
case "B":
{
qual = "Very good"; break;
}
case "C":
{
qual = "Very good"; break;
}
case "D":
{
qual = "Bad"; break;
}
default:
{
qual = "undefined";
break;
}
}
return qual;
}

Yes, we can enforce to make return statement in one position just like the code above.

But this will become obvious if we use  if statement, just like this in C#:

        String IsPositive(int anynum)
{
if (anynum>=0)
{
return "Positive";
}
else
{
return "Negative";
}
}

When I was leading a team of developers, I often found that code and when the inside if bracket the code contains another ifs and returns, the code will become hard to maintain and it’s still true until now! We will have two maintenance point of return values in that code above.

Now compare the code above in F#:

let IsPositive x = if x >= 0 then "Positive"
else "Negative"

It’s somehow quite a little bit hard to maintain but it still doesn’t violate F# convention to return value immediately. Now we can refine the function above into:

let IsPositiveV2 x = 
let evalResult = if x>= 0 then "Positive" else "Negative"
evalResult

Now we can see that evalResult is acting as the return value of the result, and we must have indentations.

If you want to explicitly specify the type of the returned values, you have to group the parameter into parentheses.

For example:

let multiplyV2 (a) (b) : int = a * b

and multiplyV2 will have this signature:

val multiplyV2 : a:int -> b:int –> int

This brings another convention: the last type in a function signature means the result/return value type.

Writing parameters of a function


Now let’s dive deeper about parameters in a function in F#.

We already have “sqr x” and “multiply a b” and we can simply deduce the parameters:

fs_function_params_377266B1

In F#, we define the function prefixed with let and the parameter is separated with white space. This white space is significant, therefore the next identifier after first parameter will the second parameter.

If we have the previous swap function: (also available in F# Tutorial template in Visual Studio)

let swap (a,b) = (b,a)

F# will translate the parameter as Tuples of a and b. And it will also infer the types of a and b as generic.

Recursive functions


Any recursive functions has to be marked with rec keyword after the let keyword.

We already have a recursive factorial sample in the F# tutorial:

let rec factorial n = if n=0 then 1 else n * factorial (n-1)

Again, notice the rec keyword after let.

Function as values (alias delegates in F#)


In all functional programming languages, functions are the same as values. This function as values is the same concept as delegates in .NET. We all know that many LINQ extension methods have delegates as its parameters, and so does F#.

For example: (taken from MSDN Library)

let apply1 (transform : int -> int ) y = transform y

The type of apply1 will be: (using F# interactive)

fs_function_values_type_547B1579

a function that has parameters of transform function that has int –> int and a y parameter with default type inferred as int, and the body of the function has transform function that takes y as parameter.

We can use the apply1 into these:

let increment x = x + 1

let result1 = apply1 increment 100

Multiple arguments/parameters are separated by “->” sign.

For example:

let apply2 ( f: int -> int -> int) x y = f x y

let mul x y = x * y

let result2 = apply2 mul 10 20

Now we can apply mul function because it has the same signature as f, int –> int –> int.

Again, in functional programming world, the last type always means the return value type.

do Bindings


We can also execute code without function definition or simply executing it independently in F#.

The way we do this in F# by using “do” binding. We can also apply attribute to a do binding.

We can use this techniques to run a code as entry point in a Windows Forms.

A sample usage of F# do binding in a Windows Forms:

open System
open System.Windows.Forms

let form1 = new Form()
form1.Text <- "XYZ"

[<STAThread>]
do
   Application.Run(form1)


Lambda Expressions


Now the fun part in F# functions: lambda expressions. The lambda expressions in F# is the same concept as lambda in C# and VB, and prefixed with keyword: “fun”. The purpose of lambda syntax is only for convenience for writing anonymous function (delegate).


A small sample of lambda:


let list = List.map (fun i -> i + 1) [1;2;3]
List.map is conceptually the same as Enumerable.Select in LINQ.


Let’s dive into this lambda deeper!


Now I will use Seq.map to project a collection to another type of collection:


open System.Diagnostics
open System.Linq


let ProcessList = Process.GetProcesses()


let ProcessNames = ProcessList |> Seq.map(fun p -> p.ProcessName)
The Seq.map works conceptually the same as Select in LINQ.


Let’s decompile it! Here’s the layout of the code:

fs_decompiled_namespacelayout_0F48FE87

F# compiler will create many compiler generated code. What will ProcessList and ProcessNames look like?

fs_decompiled_proclist01_5964096C

And now let’s dive into the generated u0024.MathModules, we’ll have this:

fs_decompiled_compilergenerated01_2E1F7265

And the call to Seq.map is available on static constructor of u0024MathModules:

IEnumerable<string> strs = SeqModule.Map<Process, string>(processNamesu004025, (IEnumerable<Process>)processArray);

And you can deduce that any Seq operation actually mapped to SeqModule class with many static functions.
Also List is mapped to ListModule respectively.

Now, where is the content of lambda?

It’s available on ProcessNamesu004025:

fs_decompiled_compilergenerated_processName_2DB33F70

Again, delegation in F# is implemented as FSharpFunc internally. And you can see its “p.ProcessName” body is in the Invoke method.

There’s another attribute to hide the other field, the DebuggerBrowsable with parameter DebuggerBrowsableState.Never on it. This also means that this class isn’t meant to be used outside.

Again, this means that F# objects and functions are available for the other programming language as well as long as you don’t have to care the generated code produced by F#.

A gentler introduction to Computation Expressions in F#


A computation workflow is one of F# unique feature comparing to C# and VB. It’s somehow can bring new constructs to your code but it also brings Monad to your everyday use of F#, in a gentler way.

According to F# definition on MSDN Library:


“Computation expressions in F# provide a convenient syntax for writing computations that can be sequenced and combined using control flow constructs and bindings. They can be used to provide a convenient syntax for monads, a functional programming feature that can be used to manage data, control, and side effects in functional programs.”


Now, we can simply assume that F# can do Monad as well! But why it is needed?

As we have discussed before in part 1 and 2, it’s common in functional programming languages to compose functions, not just using it alone or chaining it up (using the “|>” in F#).

This composition comes very handy when you want to construct a DSL or simply encapsulating side effects.

For those outside F#, we can find a sample of Monad in LINQ: the SelectMany! It composes two Func<T,U> and compose it or bind it.

The syntax is:

builder { expression }

The builder is the builder name, and the expression can contain one or more the bang statements (statements that end with !) such as let! and do! statements.

I call them statements, because F# MSDN call them just keywords but this is somehow quite confusing. These keywords need expressions, just like statements in C# and VB.

Then it’s explained further:


“In computation expressions, two forms are available for some common language constructs. You can invoke the variant constructs by using a ! (bang) suffix on certain keywords, such as let!, do!, and so on. These special forms cause certain functions defined in the builder class to replace the ordinary built-in behavior of these operations. These forms resemble the yield! form of the yield keyword that is used in sequence expressions.”


In F#, we already have computation workflow in action: async in asynchronous workflow! More async in part 8.

Here’s the list of methods available for computation expressions:

(taken from http://msdn.microsoft.com/en-us/library/dd233182.aspx )

fs_method_computation_1133B0B3

The most common use is let! keyword. It requires a builder with Bind expression inside of it. The bind will compose two expressions as long as the type is aligned well.

This is the translation from expressions:

fs_computation_translation_0A3BB041

The bind in F# inspired by bind in Haskell, and it’s quite simplified version of Haskell’s but without type classes.

Therefore, this meet the common requirement of Monad: (as explained gently by Wes Dyer in http://blogs.msdn.com/b/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx blog entry)


  1. Left identity: Identity.Compose(f) = f
  2. Right identity: f.Compose(Identity) =f
  3. Associative:  f.Compose(g.Compose(h)) = (f.Compose(g)).Compose(h) and it is equal to “f o g” = f(g(x))

Now we get back to SelectMany:

IEnumerable<TResult> SelectMany<TSource, TResult>( this IEnumerable<TSource> source,
    Func<TSource, IEnumerable<TResult>> collectionSelector)

It is the same as bind with this signature:

Bind :: IEnumerable<'T> * ('T –> IEnumerable<'U>) –> IEnumerable<'U>

Abstract that into:

Bind :: M<'T> * ('T -> M<'U>) -> M<'U>

Done, we have monads!

Suppose we want to make Monad for UI. In this sample provided by Adam Granicz from http://www.devx.com/enterprise/Article/40481/0/page/2 we can see the builder for WPF UI:

(I have edited and corrected some type information on the bind)

fs_monad_uibuilder_5F1BC48E

Using the builder above is simple:

let win =
WindowBuilder()
{ let! panel =
PanelBuilder(StackPanel())
{ let! btn1 = Button(Content = "Hello")
let! btn2 = Button(Content = "World")
return () }
return () }

win.Show() // Pops up the window in FSI.

Run the code in the interactive mode!

I have demonstrated the computation expressions with the twist of OOP in F#. It will be detailed for part 6, OOP in F#.

Next: F# standard libraries in part 5!




Further reference



  1. Monad in functional programming: http://en.wikipedia.org/wiki/Monad_%28functional_programming%29
  2. Mathematical Monad: http://en.wikipedia.org/wiki/Monad_(category_theory)
  3. Adam Granicz article of “Working with DSL and Computation Expression in F#”: http://www.devx.com/enterprise/Article/40481

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