Monday, November 3, 2014

Loop construct of C#/VB mapped into F#

Hi there, my blog readers!
The F# adventure series is almost complete, and F# adventure series is focusing on F# 3.0 in Visual Studio 2012. Meanwhile, there were questions addressed to me about the basic common feature of programming languages: loop.
For those of you comes from C#/VB world, F# actually has the same semantic loop constructs.
F# has these loop supports:
  1. for loops with n times (incremental for in C#,For Next in VB)
  2. for loops that iterate the elements of a collection/set/array (for each in C#, For Each in VB since VB 8.0 in Visual Studio 2005)
  3. do..while that perform loop with test condition (same as do..while in C#, While..Wend in VB)
To simplify giving you the samples, I’ll take samples of F# directly from MSDN Library, paste them, and add the same samples with C# and VB.
Starts from Visual F# MSDN Library: http://msdn.microsoft.com/en-us/library/dd233249.aspx
Let’s visit the three loop above with samples:



F# loop C# VB
// for loop with n times

for i = 1 to 10 do
  printf "%d " i

// incremental for

for (var i=1;i++;i<=10)
   Console.Write("{0:d}",i);
‘ For Next

For I = 1 to 10
    Console.Write("{0:d}",i)
Next

// Looping over a list.
let list1 = [ 1; 5; 100; 450; 788 ]
for i in list1 do
   printfn "%d" i
// for each
var list1 = new Int32 { 1, 5, 100, 450, 788 }
for each i in list1
   Console.WriteLine("{0:d}",i);
‘ For Each
Dim list1 As Int32() = [ 1, 5, 100, 450, 788 ]
For Each i In list1
   Console.WriteLine("{0:d}",i)
End For
// while..do


let lookForValue value maxValue =
  let mutable continueLooping = true
  let randomNumberGenerator = new Random()
  while continueLooping do
    // Generate a random number between 1 and maxValue.
    let rand = randomNumberGenerator.Next(maxValue)
    printf "%d " rand
    if rand = value then
       printfn "\nFound a %d!" value
       continueLooping <- false


// do

void lookForValue(Int32 value, Int32 maxValue)
{
    var continueLooping= true;
    var randomNumberGenerator = Rendom();
    do
    {
        var rand = randomNumberGenerator.Next(maxValue)
        Console.Write(rand);
        if (rand == value)
        {
             Console.WriteLine(rand);
             continueLooping = false;
        }
    } while (continueLooping)
}
‘ While..Wend

Sub lookForValue(value As Int32, maxValue As Int32)
    Dim continueLooping= True
    Dim randomNumberGenerator = Rendom()
    While continueLooping
        Dim rand = randomNumberGenerator.Next(maxValue)
        Console.Write(rand)
        If (rand == value)
             Console.WriteLine(rand)
             continueLooping = false
        End If
    End While
End Sub

There you have it now! All of those samples mapped from F# codes are semantically the same, although the low level IL implementation might be different.

In For Next, VB will hoist the variable of the loop limit first. But this will change after Roslyn compiler is shipped with Visual Studio 2015, as C# and VB now have the same compiler infrastructure.

Great question my blog reader, and I will include this in my completed F# adventure series!

Friday, October 10, 2014

Speaking on Lambda Jakarta: delivering intro to concurrency and asynchrony

Now it’s Lambda Jakarta meetup time! This meetup is on 4th October, 2014. Again, thanks to Traveloka for preparing the place for us to meet!

This time, Abdullah was presenting about the problem of concurrency titled: “Promise of Better Concurrency in Functional Programming: Big Win or BS?”. Yes, concurrency is everywhere now, and it’s becoming more and more relevant because of the fact that nowadays CPU is not getting speedier, but the CPU is keep getting denser with more core CPUs.

WP_20141004_004

Even on my laptop, the HP Envy beefed with intel CORE i7, it has 4 core and each core has 2 logical hyperthreading:

HPEnvy_TaskManager

This makes the logical overall CPU to be 8 logical CPUs! As we see, the clock speed is only at 2.39Ghz.

And this has becoming trend, not just from Intel. AMD has begun releasing microprocessor using this scheme/model.

Abdullah in his presentation was quoting this nice article from Herb Sutter (the Visual C++ lead dev of Microsoft) about “Free lunch is over.” published in 2005.

Herb_CPU_chart

He said that developer should not depend on CPU speed, instead they should begin to think on how to maximize the existing CPU cores. Otherwise the developed application will always run on one core and the rest of CPU core will be wasted. This of course will have negative impact not just on performance, but it will make the application to lose competitive factor of being efficient and support multi core.

Herb also added an undeniable fact of concurrency, it’s not just becoming relevant but it’s already relevant at the time of his writing!

The known concept of these maximizing cores to run at many cores, hence running multiple processes at a time is called parallel programming or on more abstract, parallelism.

This is the original link of the article: http://www.gotw.ca/publications/concurrency-ddj.htm

But concurrency doesn’t stop at just parallelism. Concurrency is also dealing with states, dealing with race conditions, and also traditional concept of operating system such as locks, semaphores, mutexes, and execution contexts.

Now execution contexts are becoming more relevant as the advances in hardware are allowing us to free us from having to wait for blocking operations such as I/O (including networks, printers). But then the software has to leverage this feature as much as possible by freeing current thread to be available for other execution context. The thread doesn’t have to be multithread, as you can still use the same thread but with different execution context.

This concept is known for asynchronous programming, or simply just asynchrony. Most programming languages handles this by providing state continuations such as “Futures” and “Promises”, or using complex callback with support for function as parameter (delegate in .NET, functional interface in Java 8, function in Haskell, Scala, and other functional programming languages).

I was also helping Abdullah to further explain asynchrony in the pragmatic perspective.

WP_20141004_016

The easiest way to explain asynchrony is if we are ordering food at a restaurant:

  1. We order the food/beverages and we are served by a waiter
  2. Waiter deliver the order list to the cook
  3. Waiter serves other customer without waiting the cook to complete our order
  4. Our order is complete, and the cook is telling the waiter by putting our finished order at the waiter tray (this is the callback)
  5. Waiter checks the tray, grabs the finished order, and delivers the order to us

I also promised the audience that the next meetup, I will deliver small presentation about asynchrony sample in detail Smile

The gory detail of concurrency is also nicely explained by this guy (formerly Oracle’s Java developer, now one of NodeJS founder) Bryan Cantrill in his excellent article: https://blogs.oracle.com/bmc/entry/concurrency_s_shysters

That’s all, folks!

This is the official landing page of this session’s Lambda Jakarta: http://www.meetup.com/Lambda-Jakarta/events/206904832/

If you live in nearby Jakarta, I encourage you to participate on this meetup, guys!

Friday, September 26, 2014

Presenting at MVP Community Camp for September 2014

Hi my blog audiences!

Why I have silent month of August? Don’t worry! Because I was preparing for participating at MVP Community Camp!

Previously, I was asked by Katherine Chen, my MVP Lead, whether I have some experiences with Xamarin tools at the end of July. I told her that I had some about 8-10 months of experiences, and the tool is strong!

This is the original official promotional ad:

MVP_community_camp_September2014

After it’s decided by Katherine, I got my own sessions:

ComCampSession_20140924

Although there were some glitches when we’re rehearsing the presentations (with the assistance of Katherine), at the time of the Lync conference, the session is fine! Unfortunately the Android emulator were unexpectedly sluggish when I was having demo of running Xamarin code.

I also gave demo of The Multi Device Hybrid for Visual Studio 2013 CTP 2, fortunately the demo went well. Smile

Sunday, July 27, 2014

Speaking on Lambda Jakarta meetup delivering F#

Hi all! Time for speaking Smile

The talk is on July 26, at Traveloka headquarter. Many thanks to Traveloka!

Before that, I have to tell you now in Indonesia we have special meetup for functional programming called Lambda Jakarta! This special interest meetup is not just functional programming as general, but for more specific interest such as F#, Haskell, Scala, Clojure, OCAML, R, LISP, RUST, Erlang as well!

Just look at their logo:

full_4361622

Found in 2011, now has more than 8 active participants!

It was an initiative proposal at Ruby Indonesia meetup, initiated by Asep. Now mentored by Abdullah (a Haskell specialist, yes he’s a damn good Haskellian!).

In this meetup I deliver mostly intro to F# but with geeky introduction specific to functional programming: “Putting the functional and fun in F#”.

Here’s the starting presentation:

WP_20140726_003

And some of the audiences:

WP_20140726_006

And as of this meetup, I pledge myself to be active participant of this meetup as well! Smile

Sunday, July 6, 2014

SPEAKING and TRAINING: Giving Functional Programming awareness in Allianz

Hi all!

I got appointed to give awareness of functional programming as now Functional Programming is everywhere! Previously this is also a part of Allianz IT application development biweekly meeting, now they wanted to have sharing sessions as well!

In this presentation, I have given 50 minutes of quick intro of Functional Programming with sample in F#. The audiences was quite many, we got 25 developers, testers and one MUGI member (he’s also Allianz employee) Smile

This presentation was held on 3rd July, 2014. Here are the pictures:

ALLIANZ_Functional_01

Thanks to this guy sitting in front of me, Joerg Sauer, or giving me time and place to present Visual F#:

ALLIANZ_Functional_02

 

Happy coding with Functional! Go Visual F#! Smile

Friday, June 27, 2014

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


Using LINQ in F# 3.0

Before F# 3.0 in Visual Studio 2012, LINQ was not available in F#. If you use F# Powerpack for F# 2.0, LINQ was implemented as computation expression.

An overview of LINQ

LINQ stands for Language INtegrated Query. LINQ has its first release in C# 3.0 and VB 9.0 in Visual Studio 2008.

Basically, LINQ is a syntactic sugar on top of C# 3.0 and VB 9.0. It is then translated by the compiler into a series of extension method calls to Enumerable (for LINQ to Object) or Queryable (for LINQ to SQL, LINQ to Entity).

Let’s look at LINQ to Object, because this is the basic foundation of all other LINQ to others.

LINQ to Object is the basic foundation because it is available for the basic foundation of all generic or typed collection in .NET: IEnumerable<T>

Why? There are always misconception that LINQ is a mean to connect to database, and the fact is not that! LINQ is a way to query a collection of data. The data can be a single type or can be a collection.

I can also query the running processes on my machine that consumes memory more than 1 MB: (using C#)

csharp_LINQ

In VB, we can also do that:

vb_LINQ

Now we can prove that LINQ is not used only to query database.

The interesting point of using LINQ is, the from, where, select is used as keywords. The compiler will translate those LINQ keywords into series of Lambda expressions.

In C#, the code will be translated into: (the commented is the original source code)

csharp_LINQ_lambda

If you see the source code very well, you’ll also notice that there are type inferences in action! But the type inferences in C# and VB are different with F#.

In C# and VB, type inferences are happened in local scope, and also for method’s parameter but not for the method return type.

F# will deduce an infer the return type of the method gracefully and flows nicely outside the scope of the methods.

F# 3.0 LINQ query expressions

Let’s dive into F# 3.0 LINQ!

LINQ in F# 3.0 was composed using monad builder, by a class names QueryBuilder. The complete fully qualified class name is Microsoft.FSharp.Linq.QueryBuilder. Don’t worry, you don’t have to use it directly because it’s composed for us to be used nicely as composable query.

In F# 3.0 the code will be:

fsharp_LINQ_simple01

The interesting aspect is the use of Seq.ofArray. Let’s say we’ll delete the use of Seq,ofArray, run the code, and display the result using the F# interactive:

fsharp_LINQ_without_seqofarray

Now with Seq.ofArray added, the result is much simpler and also nicer to observe:

fsharp_LINQ_with_Seqofarray

Without Seq.ofArray, the F# interactive will display all of the resulting array of Process.GetProcesses after it display the result of running process. Because the basic behavior of GetProcesses is eager evaluation, not lazy evaluation. Seq.ofArray pipeline will execute it lazily, only evaluate it as needed.

The type inference will infer that array of Process is a derived from IEnumerable<Process>. It is also true in C# and VB.

In the F# code, I also use sortByDescending to sort the result descending, based on the size (using property of WorkingSet64). It is equal to order by in C# and VB with descending option added.

What about the semantic? The semantic is the same, only few clause has different semantic.

This is the table of semantic and syntax differences between C#, VB and F#:

fsharp_LINQ_featurecompare

Notes:

All of the aggregates are not available in LINQ of C# and VB in a query comprehension. F# has integrated in the query computation, as with other SQL clauses (FROM, SELECT, WHERE, JOIN, GROUP BY).

Those query operations that has no semantic differences are really having the same calls to the same methods of LINQ to object. Having no semantic differences means that it’s guaranteed for F# to have the same results as in C# and VB.

We have known SELECT, WHERE, and ORDER BY in F# and a hint of “take”. They are very simple to use, and it has the same semantic although the syntax of ORDER BY in F# has different name, using sortBy.

This is F#’s groupBy in action:

(I intentionally group the processes by ProcessName, and then display the number of grouped process)

fsharp_groupby

As usual, svchost has the largest number of instances.

Note:

The groupBy sample has Count(), and this require System.Linq.
Iterating the result of group by requires us to look at the Key collection first, then the grouped data. Why?

Due to the returned result of groupBy is the same as Enumerable.GroupBy, that returns a IDictionary<Key,Value>.

It returns a dictionary because of the nature of group by: the result is grouped by a key, then each key will have values that grouped by the key.

Now, I’m going to display the maximum amount of memory taken by those process.

This is the code using maxBy:

fsharp_LINQ_maxBy

Those equalities of query operators table is not displaying all, actually. But it can be considered the same as the operations in System.Linq.Enumerable extension methods.


Further readings

Tuesday, June 10, 2014

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


OOP in F#

F# is not just a functional programming language, but it is also an object oriented programming language which also an imperative programming language.

The OOP feature of .NET are supported by F#, including interfaces, classes, inheritances, method overrides, overloads.

The classes created in F# can be used in C#, VB and others because it’s generated into the same IL that C#, VB and other have (as long as the IL is standard .NET CLR’s IL).

This OOP feature is where the flexibility of F# has risen above all other functional programming languages that only offers pure functional programming languages. But this flexibility also marks F# as non pure functional programming language.

Why? This is where the critics often attack F#. Before diving deeper into F# OOP, I'm going to introduce a very quick glimpse of OOP.

OOP often described as how you develop software using object as the main attention.

An object in OOP is an object that has attributes and behaviors, just like us humans.

Attributes can be name, address, gender, nationality. Behaviors in OOP are the common capabilities that we have, such as Walk, Run, Eat, Drink.

This is a simple illustration of human as object:

simple_oop_illustration_6F308F4D

We can often inherit our attributes (but not all) from our parents, and so does our behaviors. This is called inheritance, the most common known concept part of OOP.

 

OOP first stop: Inheritance, Polymorphism, Encapsulation

Inheritance in OOP is really what makes OOP really shines: the ability to inherit an available object with all of the visible allowed attributes and behaviors.

It is called visible allowed attributes, because there are scope modifiers at the attributes that control this visibility.

In F#, these are allowed scope modifiers:

  • public
  • private
  • internal (the scope is only assembly scope)

F# does not allow protected modifier, like those in C# and VB.

But this OOP doesn’t stop just having inheritance.

Generally OOP has these 3 concepts:

  • Inheritance
  • Polymorphism
  • Encapsulation

So, what are Polymorphism and Encapsulations?

Polymorphism is concerning the change of behavior when an object inherits other object, this is why there are method overrides that define behavior overrides.

Encapsulation means an object is known to outside by having definition of attributes (properties in .NET and C#/VB/F#) and behaviors or operations.

In F#, OOP is supported in the form of class and interface.

 

Interface in F#

Interfaces in F# are implemented in two ways:

  • Using object expressions
  • Using class types

To create interfaces using class types are quite straightforward, the syntax is similar to interface declaration of C# and VB.

This is the syntax using class types:

// Interface declaration:
[ attributes ]
type interface-name =
   [ interface ]
     abstract member1 : [ argument-types1 -> ] return-type1
     abstract member2 : [ argument-types2 -> ] return-type2
     ...
   [ end ]

This is a sample code of creating interfaces using class types (from F# in Visual Studio 2010 Tutorial template):

type IPeekPoke =
    abstract Peek: unit -> int
    abstract Poke: int -> unit

The IPeekPoke will be treated as interface and will have the same signature as declaring interface in C# and VB. By default, the access modifier when not specified is public. This interface can also contain other members not just methods, but it can contain properties:

type IConnectionFactory =
    interface
        abstract ConnectionString : string with get, set
        abstract ConnectionState : int with get
        abstract Open : unit -> unit
        abstract Close : unit -> unit
    end

The interface declaration above can also be written to omit interface keyword that ending with end keyword:

type IConnectionFactory =
    abstract ConnectionString : string with get, set
    abstract ConnectionState : int with get
    abstract Open : unit -> unit
    abstract Close : unit -> unit

The type IConnectionFactory simulates a database connection commonly found in System.Data. It demonstrate an abstract property of ConnectionString with setter (set) and getter (get), ConnectionState that has getter only, and abstract method of Open and Close.

Note that F# clearly defines that each method that has no parameter and returns no parameter has to have signature as unit, returning no parameter as unit.

To create interface using object expressions, the interface are declared within a class. This is the syntax:

// Implementing, by using an object expression:
[ attributes ]
let class-name (argument-list) =
   { new interface-name with
       member self-identifier.member1 argument-list = method-body1
       member self-identifier.member2 argument-list = method-body2
       [ base-interface-definitions ]
   }
 

member-listThis is a sample of interface implemented using object expressions:

let makePrintable(x: int, y: float) =
    { new IPrintable with
              member this.Print() = printfn "%d %f" x y }
let x3 = makePrintable(1, 2.0)
x3.Print()

The advantages of using the object expression syntax are subtle: the interface does not have to be named and the scope of the interface is not visible from outside. Concrete implementation has to be implemented directly inside the class. But the disadvantage of using this syntax is quite clear; this syntax has no comparable features in C# and VB.
Create type that implements interfaces
To create types that implements interface, the interface must be declared using class type syntax.

For example, we can create type that implement IPeekPoke interface above:

// Types: classes with interface implementations
// ---------------------------------------------------------------
/// A widget which counts the number of times it is poked
type Widget(initialState:int) =
    /// The internal state of the Widget
    let mutable state = initialState
    // Implement the IPeekPoke interface
    interface IPeekPoke with
        member x.Poke(n) = state <- state + n
        member x.Peek() = state
    /// Has the Widget been poked?
    member x.HasBeenPoked = (state <> 0)

Now, to call the method of the interface, F# requires the call to be explicit to specify the interface, and this is clearly specified in MSDN Library:

"Interface methods can be called only through the interface, not through any object of the type that implements the interface. Thus, you might have to upcast to the interface type by using the :> operator or the upcast operator in order to call these methods."

This is a sample code to call methods of IPeekPoke:

let widget = Widget(12) :> IPeekPoke
widget.Poke(4)
let peekResult = widget.Peek()

There is an alternative syntax to call interface method.

An alternative is to declare a method on the object that upcasts and calls the interface method, as in the following example, with comparison of having an added sample of using upcast of above:

type IPrintable =
   abstract member Print : unit -> unit

type SomeClass1(x: int, y: float) =
   interface IPrintable with
      member this.Print() = printfn "%d %f" x y

type SomeClass2(x: int, y: float) =
   member this.Print() = (this :> IPrintable).Print()
   interface IPrintable with
      member this.Print() = printfn "%d %f" x y

// sample usage
let x2 = new SomeClass2(1, 2.0)
x2.Print()

The code of SomeClass2 declaration define member Print that has upcast to IPrintable.Print and also has concrete implementations of Print method.

 

Class in F#

A class in F# is the same class in C# and VB. A class can have properties and methods, with fields as well.

Class in F# is quite straightforward. You can create class with no constructor or with default constructor with parameters.

Declaring a class with no constructor will imply that the class will have default constructor that has no parameter.

This is the base syntax:

fsharp_class_declaration_7A0D7095

In the preceding syntax, the type-name is any valid identifier. The type-params describes optional generic type parameters. It consists of type parameter names and constraints enclosed in angle brackets (< and >). The parameter-list describes constructor parameters. The first access modifier pertains to the type; the second pertains to the primary constructor. In both cases, the default is public.

A class that inherits from specific type is defined using inherit keyword. If there’s no inherit, then the class is automatically or implied to be derived from System.Object, just like every classes in .NET.

This is a very simple but good sample from Tutorial.fsx from F# template:

fsharp_class_sample_58419804

When you define types that reference each other in a circular way, you string together the type definitions by using the and keyword. The and keyword replaces the type keyword on all except the first definition, as follows.

This is why in MSDN called as "Mutually Recursive Types".

A sample of mutual recursive type:

fsharp_mutual_recursive_type_3CBC9601

You can also add generic type parameter for the type.

Generic in F# is declared in “<generictype>” syntax, like “<’T>” with single quote added to differentiate a concrete type or truly generic type.

This is a sample of generic in class declaration:

fsharp_generic_class_143DB3ED

 

Defining abstract classes

F# also supports abstract class. An abstract class in F# is the same abstract class in C# and VB, and it’s also semantically the same.

An abstract class in OOP is simply a class that has abstract method or properties with no implementation body but abstract class can also have concrete method.

In F#, abstract class must have AbstractClass attribute. The abstract method and properties must have abstract keyword as identifier.

Sample abstract class:

fsharp_abstractclass_sample01_7924E4DE

The class that derives from an abstract class MUST implement all of the abstract members.

Sample derived class from Shape2D class:

fsharp_abstraclclass_sample_concrete_6F1043B3

 

Declaring properties in F#

Property in F# is the same as property in C# and VB, and they are also semantically the same. This is also one advantage of F# of seamlessly interop with C# and VB to have OOP support, not just interface and classes supports.

Declaring properties is simple, using member keyword with the desired set and get.

NOTE: when defining properties, all property value  is mutable by default because of the nature of getter and setter in OOP.

Syntax:

fsharp_property_syntax_65D40872

Declaring the property starts with member keyword, with the combined get and set accessors.

If the get and set are combined, with keyword must be used.

Sample:

fsharp_property_sample01_2314BD3A

Or we can use separate set and get, like this sample:

member this.MyReadWriteProperty with get () = myInternalValue
member this.MyReadWriteProperty with set (value) = myInternalValue <- value

Begins with F# 3.0 in Visual Studio 2012, F# can use auto properties just like auto properties in C# and VB.

Sample of auto properties:

fsharp_property_autoproperty_sample_2F363761

 


Further reading

  1. Tutorial of OOP in Java (but it can be applied in .NET): http://docs.oracle.com/javase/tutorial/java/concepts/
  2. Interface in F#: http://msdn.microsoft.com/en-us/library/dd233207.aspx
  3. Classes in F#: http://msdn.microsoft.com/en-us/library/dd233205.aspx

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