Hello there!
After a very long “quiet time” in blogging, now it’s time to encourage myself to share again! But I’d love to blog in my only passion and I truly confident about: programming, especially programming in .NET and Java. Actually, I’ve written an eBook about F# before but it was way before Visual Studio 2010 launched. Now I’m focusing on F# and functional programming.
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.
Now, here are the parts:
- Part 1: Introduction to Functional Programming
- Part 2: Functional Programming Concepts
- Part 3: Introduction to F#
- Part 4: Functions, Delegates and Computation expressions in F# (you are here)
- Part 5: F# standard libraries
- Part 6: OOP in F#
- Part 7: Using LINQ in F# (and the upcoming F# 3.0)
- Part 8: F# Asynchronous workflow
- Part 9: F# MailboxProcessor
- Part 10: Units of Measures
- Part 11: F# Power Pack
- Part 12: F# for Silverlight 4 (and above)
- Part 13: A look at F# 3.0 in VS 11 (Visual Studio 2012)
- Part 14: A look of Functional Programming in VB 10 and C# 4.0 compared to F#
- Part 15: A look of F# compared to Haskell, Scala and Scheme
- Part 16: F# future and what features that F# must have
- 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)

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?

Then the decompiled version will be:

Again, it’s different, and there is CompilationArgumentCounts attribute at the multiply function.
What is this attribute, really? Seeing this on MSD Library:

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:

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

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)

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:

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)

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:

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

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

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:

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 )

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:

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)
- Left identity: Identity.Compose(f) = f
- Right identity: f.Compose(Identity) =f
- 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)

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
- Monad in functional programming: http://en.wikipedia.org/wiki/Monad_%28functional_programming%29
- Mathematical Monad: http://en.wikipedia.org/wiki/Monad_(category_theory)
- Adam Granicz article of “Working with DSL and Computation Expression in F#”: http://www.devx.com/enterprise/Article/40481
This is a quoted thread content F# and trends in functional programming in a discussion thread model, please follow my thread (my id on Kaskus is “erilive”) on Kaskus! And it’s available in Bahasa Indonesia!
Hi guys,
If you want to know more about F# and trends in functional programming in a discussion thread model, please follow my thread (my id on Kaskus is “erilive”) on Kaskus! And it’s available in Bahasa Indonesia!
There’s a lot of discussion happens there! And I invite you to join, and I will invite you all of those are advanced or just beginner in functional programming and F#. Some topics are very interesting but quite advanced such as type classes, but there is an easy topic about why functional programming matters.
Here’s the address:
http://www.kaskus.co.id/thread/000000000000000016890387/fpara-programmer-f-dan-functional-programming-disini-yah/
And paragraphs below are samples from the thread:
Monad sample
Quote:Original Posted By erilive on http://www.kaskus.co.id/show_post/000000000000000759711105/18/
Monad yang mana gan? Maybe monad, Identity monad, Reader monad, State monad?
Kalau Reader monad di F#, sudah ada yang bahas:
http://codebetter.com/matthewpodwysocki/2010/01/07/much-ado-about-monads-reader-edition/
Dan sepertinya kalau diimplementasikan di bahasa selain F# (kecuali kalau di Haskell) sepertinya akan menjadi kurang elegan.
Monad disini bukan "Monad" di cabang matematika Category Theory.
Kalau memang banyak peminatnya, akan saya jelaskan Monad di thread ini, agan-agan :)
Notes in English: (as translated)
Which Monad? There are Maybe Monad, Identity Monad, state Monad.
Reader Monad sample in F# has been discussed in:
http://codebetter.com/matthewpodwysocki/2010/01/07/much-ado-about-monads-reader-edition/
And if it’s implemented in other language besides F# and Haskell, it’ll be less elegant.
Monad in this context is not direct equals to Monad in Category theory from Math discipline.
Quote:Original Posted By Syinn
silahkan aja kalo mau langsung bahas monad, saya nyimak dulu ...kalo ada yang kurang ngerti , akan saya tanyakan pada anda
ada baiknya bahas yang awal dulu, yakni monad state
Dan sepertinya kalau diimplementasikan di bahasa selain F# (kecuali kalau di Haskell) sepertinya akan menjadi kurang elegan.
btw, saya ingin tahu kenapa om bisa berkesimpulan yang saya bold di atas ? bisa anda jelaskan secara tehnik dan detail?
karena soal keeleganan code pemrograman kan tergantung kreatifitas programmer itu sendiri, apapun bahasa program yang dia gunakan (ini kalo menurut saya lho, om )
Note in English:
He (Syinn) wanted to know about why I told him it’s less elegant.
And here’s my answer:
This is state monad in F# and sample code to use:
module StateMonad
let (>>=) x f =
(fun s0 ->
let a,s = x s0
f a s)
let returnS a = (fun s -> a, s)
type StateBuilder() =
member m.Bind(x, f) = x >>= f
member m.Return a = returnS a
let state = new StateBuilder()
let getState = (fun s -> s, s)
let setState s = (fun _ -> (),s)
let Execute m s = m s |> fst
Now, in C#: (taken from http://taumuon-jabuka.blogspot.com/2012/06/state-monad-in-c-and-f.html)

The Bind operator is implemented below:

As you shall see, it’s less elegant!
Why IO Monad is “EVIL”?
Syinn asked again! But the topic is about why IO Monad is “EVIL”:

Here’s my answer: (and apologize if it’s quite long)
There is a blog post that describe IO Monad is evil: http://kawagner.blogspot.com/2007/02/why-monads-are-evil.html
And I assume he (Syinn) quoting that blog post although he didn’t mention it.
My definite answer is: IO Monad isn’t evil. According to that post, because value evaluation when designing IO Monad became imperative, and therefore it would break referential integrity. But it’s not! Because the nature of Haskell is non strict (lazy), the timing of the execution is not so important and the reference is not broken.
A simple sample of this is when dealing with iterator of yield in C# (since VS 2005) and in VB.NET (since VB 11 in Visual Studio 2012).
Due to the fact that I/O is side effect, then declaring I/O must be explicit and has to be marked as signature to a part of the “world” that includes garbage collection.
Functional programming, especially the "pure" ones, forces us to be aware and be careful in handling side effect such as I/O, pointer, exceptions.
More on this?
You will have it on my part 4, 5 of functional programming series! Watch for my next blog post entry!
Hello there!
After a very long “quiet time” in blogging, now it’s time to encourage myself to share again! But I’d love to blog in my only passion and I truly confident about: programming, especially programming in .NET and Java. Actually, I’ve written an eBook about F# before but it was way before Visual Studio 2010 launched. Now I’m focusing on F# and functional programming.
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.
Now, here are the parts:
- Part 1: Introduction to Functional Programming
- Part 2: Functional Programming Concepts
- Part 3: Introduction to F# (you are here)
- Part 4: Functions and Delegates in F#
- Part 5: F# standard libraries
- Part 6: OOP in F#
- Part 7: Using LINQ in F# (and the upcoming F# 3.0)
- Part 8: F# Asynchronous workflow
- Part 9: F# MailboxProcessor
- Part 10: Units of Measures
- Part 11: F# Power Pack
- Part 12: F# for Silverlight 4 (and above)
- Part 13: A look at F# 3.0 in VS 11 (Visual Studio 2012)
- Part 14: A look of Functional Programming in VB 10 and C# 4.0 compared to F#
- Part 15: A look of F# compared to Haskell, Scala and Scheme
- Part 16: F# future and what features that F# must have
- 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:

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:
- functional
- immutable
- succinct
- 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.

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

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?

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)

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:

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#:

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#:

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:

While in C#:

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:

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

Declaring type is simple, use “:” after the symbol name.
Now when type inference is used in a function declaration:

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)

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:

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:

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:

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:

to function declarations:

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:

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:

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

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:

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?

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
- 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
- Download the old BASICA, GWBASIC, and also VB 1.0, http://deger.republika.pl/Download_MS_Basic_versions.htm
- My F# on Visual Studio 2010 Beta 2 slide on Microsoft Docs, http://docs.com/ZBH
Hello there!
After a very long “quiet time” in blogging, now it’s time to encourage myself to share again! But I’d love to blog in my only passion and I truly confident about: programming, especially programming in .NET and Java. Actually, I’ve written an eBook about F# before but it was way before Visual Studio 2010 launched. Now I’m focusing on F# and
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.
Now, here are the parts:
- Part 1: Introduction to Functional Programming
- Part 2: Functional Programming Concepts (you are here)
- Part 3: Introduction to F#
- Part 4: Functions and Delegates in F#
- Part 5: F# standard libraries
- Part 6: OOP in F#
- Part 7: Using LINQ in F# (and the upcoming F# 3.0)
- Part 8: F# Asynchronous workflow
- Part 9: F# MailboxProcessor
- Part 10: Units of Measures
- Part 11: F# Power Pack
- Part 12: F# for Silverlight 4 (and above)
- Part 13: A look at F# 3.0 in VS 11
- Part 14: A look of Functional Programming in VB 10 and C# 4.0 compared to F#
- Part 15: A look of F# compared to Haskell, Scala and Scheme
- Part 16: F# future and what features that F# must have
- Part 17: Retrospective
Functional Programming Concepts
Now it’s time to dive and discuss more of functional programming concepts. Again, functional programming has a very long history, but as I already said in part 1, you are already used it everyday (especially when you’re a Microsoft .NET developer).
A nice sample of everyday functional programming: Microsoft Excel!
Why? Microsoft Excel’s formula is always a “pure function”, once you fill the formula, the result will always be the same.
Try this in Excel:

In the cell C3, we see formula of “A3 * B3”. Once we fill in the formula, we can be sure 100% it will always return the same result no matter how many times you call the formula. Excel’s formula then also can be said as function as data. Because then you can pass the formula to other cell. This concept is called “function is first class” and there’s no difference of function and data.
Sidenote on function = data:
This can make most of us confused, because the nature mindset of common OOP programmers always separate functions (operations in OOP) and data. It’s different from the famous work of Nicklaus Wirth in “Algorithm + Data Structures = Program”. But I personally recommend to buy this book, because it’s still a very important resource for software developers.
Why is there no difference? The content of formula in C3 can be regarded as data to be passed to other operations/formulas in other cells, just like this:

So we are already familiar with Excel, and I’m sure many of us are using it everyday! I can also safely say, Excel is the most used functional programming!
To make our adventure to be more fun, this Excel sample is the most understandable sample but then again, let’s go back to our developer domain, the codes and the concepts.
Why do I bring the concept first? Please walk the path, apprentice.
The journey of thousand miles begin with a single step.
- Sun Tzu
Let’s begin with the first mile, shall we?
What makes a functional programming language?
A functional programming language is simply programming with math functions. A function is simple: an operation that takes parameter and (must) return a result.
Then again this operation in math usually always return the same result.
First of all, functional programming always take at least a parameter and return a result.
These are the concepts that really makes it shine:
- Function as first class citizen
- Fun with Currying in functions and introduction to tuples
- Higher order functions
- Pure functions
- Recursions (recursive operations)
- Type inference
- Strict (eager) evaluation versus non strict (lazy) evaluation
Let’s dive into #1 to #6 first in detail and #7 in short overview. I’ll discuss #7 details on part 3, because this topic is dealing on the nature how F# evaluate expressions in functions.
Function as first class citizen
On the entry of first class function on wikipedia, it means that language supports to pass functions as arguments (parameters) to other functions. But this functions as first class citizens isn’t just this, it also means that functions and data structure has no difference.
This matter is nicely wrapped in MSDN Library documentation on F# about F#’s first class functions:
Typical measures of first-class status include the following:
- Can you bind an identifier to the value? That is, can you give it a name?
- Can you store the value in a data structure, such as a list?
- Can you pass the value as an argument in a function call?
- Can you return the value as the value of a function call?
You can check the MSDN Library first and then try to understand what are those concept with the samples provided, but I myself can’t simply grab the concept at first.
A word of notification of this part sidenote:
I’m not simply copying and pasting from MSDN Library. Some of the words and sentences in MSDN Library is quite hard to understand at first, but always make your precious MSDN Library documentation as your first source of information, because it’s the official way to get information about .NET and also .NET programming language family from Microsoft. This blog entry will try to provide you easier way to understand what is on the MSDN LIbrary description about F# first class functions.
For the next parts, I will keep quoting MSDN Library and always give more simpler definitions and with samples.
About why there are more capture of VS 2010 F# Interactive?
Begins with this part, I prefer more to give you a captures of VS 2010 IDE and F# Interactive.
My main goal is to show you the type signature and the resulted output of F# Interactive, rather than going thru full IDE and debug. By seeing the result and the type signature, you will have more understanding of functional programming power features such as currying.
Also this will give us immediate results to know and to test what’s our code doing. This distinguish F# feature is the distinctive feature that looks like other kinds of dynamic languages such as Python and Ruby but C# and VB.NET currently doesn’t have it yet. Again, the F# interactive can be considered as also REPL capability of F#! More sample of this interactive scripting? Follow the rest of this part, guys.
From the four measures, the last two are the main traits of “higher-order function” according to MSDN Library:
The last two measures define what are known as higher-order operations or higher-order functions. Higher-order functions accept functions as arguments and return functions as the value of function calls. These operations support such mainstays of functional programming as mapping functions and composition of functions.
Keep in mind for now about the higher-order function matter “mention” from MSDN. But the content only said that, not further explaining about what “higher-order function” really means.
More on what is higher-order function? Later also in this part. But let’s walk thru those four questions of first class citizen thing.
Bind identifier to the value
Common in functional programming, the act of assigning value to an identifier is “binding”. This value assignment is different from value assignment of OOP, which value can be modified later and also can be modified many times.
Once you bind the value, it can’t be changed.
Functions in functional programming can be represented by a function symbol such as f(x) or also by a defined symbol such as y.
f(x) = y
by then, y can be considered as symbolic variable of f(x), not just the result. Again, this is different from the OOP we used to have, that y is only the result of the operation.
The function value itself can be an operation like this:

Yes, squareIt is a function that contains operation that needs parameter (argument) n, the operation is “n * n”.
F# then can make the syntax above shorter without “fun” keyword:
let squareIt n = n * n
The function is named “squareIt”.
Store the value in other data structure such as list
Using the squareIt above, we can create a list of functions in a list (or collections in .NET).
But first, let’s create a function called doubleIt:
let doubleIt = fun n –> 2 * n
If we want to create a list that has squareIt and doubleIt, we have to be sure that they must have the same signature.
Because squareIt and doubleIt already has the same signature, we can create the list that has them, like this below:

The function signature of doubleIt and squareIt is the same:

As you can see above, the signature is “int –> int”.
This means it takes a single argument with type Int32 and returns an Int32 value. Why? Because F# (and so other functional programming language such as Haskell and Lisp) has type inference built in, and it’s by default give Int32 as its type. More on type inference later.
For those .NET developers, we all know we have Delegates that represents a function. But functional programming takes it further: it also supports pairs of tuples as parameter, if the argument is more than one. More than one? see Fun in currying in functions topic later.
Pass the value as an argument
If the value has first class status, you can pass it as an argument in other function.
For example:

The symbol “greeting” has “Hello” as its value. We often see this in other languages, including non functional such as VB and C#.
What about functions?
MSDN Library said this:
If functions have first-class status, you must be able to pass them as arguments in the same way. Remember that this is the first characteristic of higher-order functions.
Yes, we must have the abilities to pass function as arguments of a function as well. This “in the same way” means in the same way as we treat data/value that passed as an argument to a function.
MSDN Library has this as a sample:

But unfortunately, the sample above is including sample of a higher order function that’s composed from combining or chaining functions.
Why? Because most functional programming families can return a function, not just having function as argument.
Look at the applyIt:
let applyIt = fun op arg –> op arg
The applyIt function is equal to a lambda that take an op and arg, and it returns a function that takes op returns an arg.
The function applyIt2 has the same meaning of the applyIt above.
But to be honest, do you find it’s easier to read and understand? Not for me.
Want more on this but in a simpler? Please see “Fun with currying in functions and introduction to tuples” topic later.
Return the value from a function call
This is the last trait of “functions as first class citizens” but it’s also important: function can be returned from a function call (as a return value).
Let’s start with a simple sample. Usually, a function returns a value that is simply a result value of a simple type, either primitive or a complex object. This is also known available in other programming languages as well, not just functional.
Simple function like this:
let multiply a b = a * b
will return a result of a x b.
But functional programming takes it further: it can return a function.
MSDN Library emphasize it:
The ability to return a function as the value of a function call is the second characteristic of higher-order functions.
Let’s look at MSDN Library again and put the sample into code in VS 2010:

First, we have checkFor function with item as parameter. I haven’t give the type for the parameter, but because the code body of checkFor is including the call to List.exists, then the type of returned function of “functionToReturn” is “ list –> bool “. This happens because List.exists return bool.
The type of “item” argument is further checked because there is a comparison of equality in the body of a lambda function of “(fun a –> a = item)”. Therefore type inference in F# will also mark the “item” argument has to have implementation of equality in F# (almost analogous with IEquatable and IComparable in .NET).
This mark is noted with “when” keyword to mark as a constraint.
Another thing is: item is then safely assumed to be generic as long as it can have equality operation.
This is also a sample of powerful of type inference in F# in action! More on type inference later in this part.
This other sample from MSDN is slightly more complex but with comments:

Sample above also features heavy currying. Move on next: have fun with currying and tuples!
Fun with currying in functions and in introduction to tuples
Any functional programming languages family have the ability to currying and use tuples. Both of these concepts are so powerful and convenient, not to mention it’s also helpful to ease complex operations in composite functions.
Also the use of tuples makes writing functions and manipulating it more fun!
In part 1, I have shown you the recursive Fibonacci function. In the F# interactive below, you’ll see the type signature of the function (not just the type of the parameter.

Sidenote on F# interactive:
You may wonder what really F# interactive is. It is a “wrapper window” to host F# Interactive prompt. F# Interactive itself is a command line executable to perform directly REPL (Read Eval Print Loop) interpreter of F#. It has its own call stack because it can remember function definitions.
You don’t have to know all about REPL, but if you want to know more, visit the CommonLisp tutorial at http://www.gigamonkeys.com/book/lather-rinse-repeat-a-tour-of-the-repl.html for more detailed information and samples.
The signature of function fact is:
fact : int –> int
means it takes argument with integer type, and returns a result of integer.
What happens if I give multiple arguments?
For example, I want to have function that multiplies a and b, I can write this:
let multiply a b = a * b
using F# interactive, I can check the type signature:

Yes, it may confuse all of us. But it’s simple: it takes an argument of int, passed as function that needs an argument of int, then return an integer.
Functional programming languages especially Lisp, ML language family and Miranda knows this well as implementation of Currying.
ML language family (including F#) has tuples, not just using currying as parameter.
Let’s do currying!
What is currying? The term currying has a very long history. It was taken from the name of Haskell Curry, a famous American mathematician. Haskell language itself also from the name of Haskell Curry. Neat!
The base theory of currying is from combinatory logic. It is basically how to compose and compose chain of functions (as long as the return value is the same type). Although it’s part of computer science, it’s actually part of mathematics especially calculus and mathematics’ logic.
Currying takes from Lambda calculus discipline. It’s a way to transform multiple arguments of a function then turn it into a chain of function arguments.
For example:
multiply int –> int –> int
is the same as
multiply(int) –> (int –> int)
the longer meaning is: function multiply takes a and return a function that takes b and return c. In other hand, I can replace second parameter with function that has int –> int as signature.
So, I can write other function as parameter to multiply:

And the code will display 30, as a result of 5 * 6, where 5 multiplier comes from multiply5 function.
Try to do this in other languages such as C# and VB? You can’t. There’s no syntax support for this.
Sidenote on multiply sample:
Actually, this sample comes from a question in Stackoverflow that asked about currying in F#. I was learning from this question too.
As a matter of fact, this is why I said earlier that MSDN Library is not clear enough to explain the concept of functional programming especially on function currying, even though it has samples, like the one about the function of applyIt2 before. This is why I have to look elsewhere.
Therefore, let’s see this sample again:
f(x –> y –> z) = f(x –> (y –> z))
Then the currying has to be right associative. For more than 3 arguments:
f(a –> b –> c –> d) = f(a –> (b –> c –> d)) = f(a –> (b-> (c -> d)))
It is always pushed toward the rightmost expression first. So in the sample below, this expression on the right is wrong in currying:
f(a –> b –> c-> d) <> f(a –> (b –>c) –>d) // <- THIS IS WRONG! It is not equal.
There’s also number of samples to do this in C# and VB, but it’s with the help of partial function application concept and full use of lambda expressions.
Not just using common curried functions, ML family languages have the ability to use Tuples as arguments.
Meet the tuples
In the sample tutorial from Visual F# “F# Tutorial” project templates, you will find many simple samples. Just add new project to an opened solution like this picture below:

In the sample, you’ll see this:

Basically a tuple is a list of unnamed but ordered elements or values. It is unnamed, but it is ordered in the order of values given. This will also determine the type of the tuple.
The sample above is then translated into this:

This is why it’s called ordered elements instead of just elements, because the order is important.
If you define the tuple as (1, 2, 3) then the signature is “int * int * int” and this means that the first element is int, second element is int, third element is int.
The value of dataB is typed as “int * string * float” and this means that the first element is int, second element is string, third element is float.
The Swap is a function that takes tuple as its arguments, and the return value is a tuple with different order of elements. But swap itself is a sample of a curried function with a single argument, as you can see the “->” in the signature of “ ‘a * ‘b –> ‘b * ‘a ”. The “ ‘a “ and “ ‘b “ in F# means that it’s inferred as generic type.
It’s quite powerful to combine currying with tuples! This is why I called I have fun using currying and tuples.
Please don’t confuse the “*” in the signature, it doesn’t mean multiplications at all.
Sidenote on tuples:
Tuple in F# was not available in .NET before .NET 4.0, although tuples in F# has been available from first release of F#.
Fortunately for us, F# tuples is now a part of .NET 4.0 and of course will also be available in .NET future releases. More on Tuple? Later on “Part 3: Introduction to F#”.
Wait, there’s more! Because function is also a value in functional programming, we can also make tuple but the elements can be typed as functions. Again, also on Part 3.
Higher-order functions
A higher-order function is simple. It is simply a function that takes other one or more functions as its arguments and then return a function. As explained earlier, these are two traits of functions as first class.
I have already provided samples in F#, but I bet many of us are still juggling in C# or VB (or both if you’re a polyglot like me)
The easiest sample is by investigating how .NET 3.5 (and above) LINQ’s “select” work. A select in SQL is simply a projection, that map each element in a list to other element in other list. Therefore it can be considered as map function.
Sidenote on map or projection:
This map is relatively the same as Map in MapReduce, the popular algorithm invented by Google to scale massive dataset processing.
This “select” projection in LINQ is very easy to understand, as it takes delegate of Func<TSource,TResult> that performs operation on each element to be projected. Most of the other SQL clause such as WHERE and ORDER BY are also implemented to take delegate as parameter.
Let’s look at the Select method signature in C#:
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TResult> selector
)
In the signature, the function is included as parameter.
Sidenote on extension method:
The this marker on first parameter signifies that this method is an extension method of IEnumerable<T>, or you can make extension method with <Extension> attribute in VB, due to the difference on how the compiler work in C# and VB.
Also starting from this part, I will encourage you my dear readers, to be a real polyglot software developers, not just being coupled to one or two programming languages and also not just using them.
Inside the body of the select, this is the code: (because TSource and TResult are generics, I can simply replace them with T and U)

Yes, it takes delegate as functions to operate on each element.
What about map? Map in F# has this signature:

It has the same effect as Select in LINQ, but it uses curried syntax and semantic.
As a matter of fact, SQL queries of SELECTs are samples of (partial) functional programming in action by looking at how LINQ is implemented. An entry of functional programming in Wikipedia also states this. But LINQ goes further, because the nature of .NET that it can returns delegate, hence function as the result.
I said partial, because the original SQL SELECT cannot return operations, only returns a list of data or a simple scalar value.
For more fact on why SQL SELECT is functional, you can do this:
- Perform a subqueries on WHERE clause, not just simple conditional clause such as “Employee.PK IS NULL”.
- Perform nested SELECT. The nested select itself is a sample of operation as parameter.
- The returned result of subqueries is immutable, you can’t modify it again. To modify it, you have to make assignment to other variable or alias to other name.
This ability comply with the trait that we can pass function as argument. The data returned on SQL is simply a list, therefore it doesn’t satisfy a second trait, the returned result can be a function result.
Why do we call it “higher-order”? Because the function that has functions as arguments has higher order of the way we look and analyze the function, therefore it has higher abstraction. Other function such as Sin(X) is simply a first-order function.
The concept of higher-order functions are also useful in function compositions.
We are familiar with this notation:

The left hand expression reads “f circle g”. Function f is called higher-order function, and function g is called first-order function.
For example:
f(x) = x ^ 2
g(x) = x + 3
so,
f(g(x)) = f((g(x) ^2)
We can “open” the parentheses in the right hand expression and then make it more natural in order of operation:
f(g(x)) = g(x) ^ 2) => (x + 3) ^ 2
in F#, we can simply do this: (the exponentiation operator in F# is “**”)

If I call f_circle_g 5.0 the result is 64, because:
f(g(5)) = (5 + 3) ^ 2 = 8 ^ 2 = 64
It’s more succinct, and it’s a proof that every function in F# is higher-order function. Can we do this in C# or VB with less noise?
As in the law of math, f(g(x)) is not equal to g(f(x)).
Proof: modify the code above to do this:
let g _circle_f = g << f
and see it.
Pure functions
Pure function means a function that will always return the same result (as long as the argument has the same value) no matter how many times we call it. Therefore it shouldn’t have side effects that may be affecting the result of the function.
This side effect is including error exceptions, I/O access, or any state affecting the output of the result.
For example:
let f x = x * 2
this function is a pure function. No matter how many times you call it with the same argument value, it will return the same.
A call of f(2) will always return 4.
But if we call a function that returns current date and time, it’s not a pure function, because it will always return the latest date and time.
To simplify this, look at this F# example:

This anytime function will return the latest time, but every time we call anytime, it will return different result. Therefore anytime is not pure.
This flexibility in F# also means that F# itself is not a purely functional programming language, because F# is able to mix pure and non-pure (impure) functions and operations. F# itself (and so other OCaml language family) still accept exception handling as part of its features.
Next, one of the important aspect of a functional programming: recursions.
Recursions (recursive operations)
A recursion is simple: an operation that execute the operation itself. Put it simply in a context of functional programming and imperative programming: a recursion is an implementation of a function that called itself.
Recursion has its roots in computer science. Wikipedia said:
Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem.[1] The approach can be applied to many types of problems, and is one of the central ideas of computer science.
The [1] note mark points to chapter 1: Recurrent Problems of “Concrete Mathematics” book by Donald Knuth, Ronald Graham, Oren Patashnik. Personally I would not recommend this book as a reference, because it’s not quite easy for me (and some of my close friend such as Nicko). It might be easy to understand for those that has backgrounds in math or pure computer science.
Sidenote on Computer Science mentioned in this series of F#:
Please don’t mix Computer Science with Software Engineering. Many large companies and most universities in Indonesia often mix these as the same discipline, but it’s not the same in nature and in curricula. Computer Science deals with the science of computation and raw programming language theories including discrete math, automata, compiler, and basic calculus. Software Engineering deals with how to develop software (including methodologies such as waterfall and iterative) with only a small portion of introduction to common programming language (such as C++) and OOP.
It really hurts my professionalism and my common sense as a real polyglot software developer. Unfortunately, this misunderstandings continues.
A good sample is the list of courses from RMIT Australia: http://www.rmit.edu.au/browse/Study%20at%20RMIT/Types%20of%20study/Degrees/Computing%20and%20information%20technology/
More on this (and also polyglot) on part 17, Retrospective.
Let’s revisit the factorial sample from part 1:

We can see that fact function is recursive by looking at the function body. And by looking at the “pattern” of “0 –> 1”, you can also see that there’s a limit of execution. It will stop when the argument is equal to 9, because it will immediately return 1 as a result of fact(0) and it’s also the same as the math equivalent:
0! = 1
To create a recursive function, IBM Developerworks has nicely summarized it:
- Initialize the algorithm. Recursive programs often need a seed value to start with. This is accomplished either by using a parameter passed to the function or by providing a gateway function that is nonrecursive but that sets up the seed values for the recursive calculation.
- Check to see whether the current value(s) being processed match the base case. If so, process and return the value.
- Redefine the answer in terms of a smaller or simpler sub-problem or sub-problems.
- Run the algorithm on the sub-problem.
- Combine the results in the formulation of the answer.
- Return the results.
The base case in point #2 is the “final escape” to immediately return a value or stop, instead of infinitely calling the function again. This is often called a “limit” or “boundary condition” which the recursive function must have.
The point #3 is very challenging: we must identify the problems into smaller sub problems that has the same way to solve as identified in point #4.
For more info, visit the link at the end of this part.
As a consequence of calling the same function inside the function’s body, the runtime needs to keep a location to remember where the self calling execution start, in order to gracefully return to previous caller. Therefore a recursive function can be dangerous to run if it’s ran many times without checking the limit of available stacks, therefore most programming languages will give error quite similar as “Stack overflow”. This indicates that the code is using all of available stacks and running out of them.
Yes, we can write factorial in a more verbose such as this in VB.NET:

Now you have it, although it’s noisier. The base case is if x = 0 then return 1, the simpler problem is after “Else”.
Hint sidenote:
Try create a factorial in C# or VB.NET like that sample above and execute the factorial function with very large number such as 50000. And see for your self what happened.
If you have smaller argument value such as 10000, the code will not catch exceptions/errors, but the result may vary. The code will result a value larger than Int32, therefore larger integer needed to store it.
In the case of VB.NET 10, the console will output "”Infinity”. In C#, it display 0. I’ll leave it to you why is this different.
There are more behavioral differences to this than simple C# and VB.NET. Microsoft has done many things in bringing these two language closer, but there are still more glitches. Why should you care? Because not many of us are just C# or just VB developer.
In most common functional programming language, this stack overflow can’t occur if the compiler is smart enough to know that it can be compiled using “tail call recursion optimization” as long as the platform infrastructure allows it.
Tail call is simply a function that its result is immediately used as the output of the function. F# compiler is smart enough to know what is recursion or not with the help of rec keyword. More on tail call on part 3.
But our F# factorial is still not quite a good sample, because a limitation of Int32 type length in .NET. Also if you use Int64, it will be limited. You can also use
Then why recursion is part of functional programming traits? I’m curious, and you should be.
Because the answer lies in the nature of how we describe math functions when we perform factorial loops in math: it can be represented recursively, not just iterative that is normal and the default way in imperative.
Let’s revisit factorial in piecewise notation:

If we focused in using the recursive, it’s more natural and it’s easier to understand than using the iterative notation of single capital Greek “PI”. The use of recursive in our code will also benefit more, because there’s minimal risk of changing internal values and also minimize or avoid the use of mutable value.
To return value, simply call the function again until it reaches the limit or boundary condition.
Type inference
Type inference is a feature of interpreting the type system of any variable used without specifying the complete type name. The type system will automatically set default type depends on any value used, but there are some conditions to be taken care of.
Those of you that already used Visual Studio 2008 and .NET 3.5 will recall that C# and VB has heavy uses of this in LINQ, and many of you may guess that this .NET 3.5 is the first version of type inference introduced in our .NET programming family. Is it right?
You are definitely wrong.
In .NET 2.0, C# 2.0 already has it. And you can see it in action on the code of Select before (without the this keyword on method parameter). The code above will work smoothly on .NET 2.0. Why?
Let’s revisit the Select code and dissect it: (I have modified the var and replace it with T, and wrap this method in a static class named “QueryComprehension”)

Now test the code using this simple sample:
Display any running process and map it to just process name:

As you see, the GetProcessses() returns an array of Process.
This is then can be used as an argument as IEnumerable<Process> because an array of Process is also implicitly implements IEnumerable<Process>. Then the T is typed Process. The anonymous delegate will also infer <Process, String> based on the return type of ProcessName which is also String, then wrap it up in an IEnumerable because of the yield iterator.
But F# has gone further, the type inference is flowing thru the code, and it’s also flows in the curried functions. This technique is known in other ML language family, based on the work of Hindley and Milner.
The type inference of F# used is typed lambda calculus.
Sidenote on lambda and calculus mentions:
Lambda calculus is taught in computer science, not just in pure Mathematics. But if you follow my explanations and always check MSDN Library, I’m sure that you will understand why it’s very important to know some aspect of real computer science, not just using the implementation of it in day to day software development.
Other concept of side effects, lambda, and then Monad in the next part may hurt your head to learn it, but please bear with me because they are inescapable properties of functional programming.
The work of Hindley and Milner was later enhanced and formalized, thanks to the work of Luis Damas.
ML language family used typed lambda calculus instead of untyped lambda calculus. Why typed lambda instead of the opposite, the untyped?
Before we dive into this, let’s have a quick visit to the basic theory of what a programming language is made of.
A programming language usually must satisfy this:
- Turing complete
- Has data structure, therefore has to have type system
- Has reasoning about how the code will be parsed and compiled
A Turing complete means the programming language must be able to simulate other general purpose computer and/or programming language within the limit of finite memory and therefore, linear bounded automaton. If some of you have studied Informatic Engineering (a.k.a. Teknik Informatika in Indonesia) then you are lucky, this is part of Compiler theory and Automata as subject. But I won’t dive into it now, because it’s part of Computer Science.
It must be, because its nature of explaining the essence of how programming language’s compiler works, not emphasizing on how you develop software application.
And so are the others: data structure, type system, and programming language reasoning.
Turing complete also means that a programming language should be able to do what other general purpose programming languages do, this includes doing looping, branching, and calculations of data, not just displaying output. As a consequence of this, a formal type system has to be defined to satisfy and to understand kinds of data to be processes.
Sidenote on type system:
At the end of this 17 parts of adventure, I will dive into “Type System” as part of my effort to simplify most of the basic theories of programing languages, the type system. This is including functional type system.
If you want to know more about type system than waiting for me to finish this article, I highly recommend you to read the one of the ultimate book of computer science, the TAPL book: “Types and Programming Language” by Benjamin Pierce. Although I personally don’t have background on computer science, I highly recommend you to buy and read this book.
Type system is put it simply: a set of rule for governing how types is interpreted and then further processed in a programming language. This rule include the static typing and dynamic typing programming languages.
Static typing means the type must be defined and the typing is constant. For example, once you defined a variable as Int32, then you will always bound the variable to be typed Int32 as long as the program runs.
Dynamic typing means the type can change at any time when needed, therefore the type declaration is not mandatory or even necessary. This typing is called dynamic, because it is not static all the time.
We used to know static type language such as C#, VB.NET, Java, F#, and all of the other functional programming languages including OCaml family, Miranda, Haskell.
Dynamic type languages are many; some of them are Javascript, Ruby, Python.
F# is static typed, so are C# and VB. Let’s see the samples.
We used to see this in C#:
String abc = “abc”;
Int32 a = 0;
or this in VB:
Dim abc As String = “abc”
Dim a As Integer = 0
But type inference in C# since C# 3.0 making it simple:
var abc = “abc”;
So type inference means deducing (or translating) the type, using dependency on the result value equation without declaring the full type before.
But ML languages such as F# goes further, for example:
let sqr x = x * x
The type of x is default to Int32, therefore the return result of sqr(x) will be typed Int32 as well.
Try to do this in C# and VB? You can’t do type infer on the function declaration of return type of the function.

Now, add some new function and use float literal and see what happens next:

It’s incredibly powerful and creepy, isn’t it? Creepy, in a sense that the type will be inferred base on the expression of the next value/usage, although all of this will happen at compile time.
Not just F#, because type inference in all of the OCaml family includes type inference in functions and also in currying functions and tuples!
Also depends on how you write the functions and the operations, the type will be inferred according the operations.
Also F# when used in scripting or interactive will change the type inferred accordingly, based on the parameter usage of the function.
It doesn’t stop here; F# can also infers types and expressions using automatic generalizations. Again, VB and C# doesn’t have this yet, and neither other OCaml family language. I will dive more of this on Part 3 and Part 4.
Strict (eager) evaluation versus non strict (lazy) evaluation
The fact that it’s all about functions and expressions, it also brings more consequences that in order to fully guarantee immutability, the value of a function result has to be safe (will always return the same) because it’s pure. Therefore it can be later safely evaluated when needed. This is often called lazy evaluation
The opposite is eager evaluation, where function is eagerly evaluated immediately.
This is why functional programming languages are often divided into these kind of evaluation strategy.

Then how to see this in action? You can do it using debugger.
Using the C# previous code of Select, you can debug the code.
The code to test and mark the line to debug is here:

Now, run the code.
When the debugger reached the breakpoint, step into it. The execution flow will step to the foreach!
Step into it again, then the debugger will go to the body of the Select method and iterate the foreach.
This proves that lazy evaluation is in action, simply it will evaluate only if the IEnumerable is iterated. What about in F#? More on this on Part 3!
Further reference links
These are further links of part 2:
- Currying on Wikipedia, http://en.wikipedia.org/wiki/Currying
- Sample of fun with currying on Brian Mc Namara’s blog, http://lorgonblog.wordpress.com/2008/04/03/f-function-types-fun-with-tuples-and-currying/
- MapReduce tutorial from Google, http://code.google.com/edu/parallel/mapreduce-tutorial.html
- IBM Developerworks tutorial on “Mastering recursive programming”, http://www.ibm.com/developerworks/linux/library/l-recurs/index.html
- Coevolution of C# and VB as part of C# and VB future, a session of Luca Bolognese on PDC 2009: Future directions of C# and VB, http://channel9.msdn.com/Events/PDC/PDC09/FT11
- Hindley-Milner why is so cool? Daniel Spiewak explained it in a blog entry: http://www.codecommit.com/blog/scala/what-is-hindley-milner-and-why-is-it-cool
- F# automatic generalizations in MSDN Library: http://msdn.microsoft.com/en-us/library/dd233183.aspx
Hello there!
After a very long “quiet time” in blogging, now it’s time to encourage myself to share again! But I’d love to blog in my only passion and I truly confident about: programming, especially programming in .NET and Java. Actually, I’ve written an eBook about F# before but it was way before Visual Studio 2010 launched. Now I’m focusing on F# and
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.
Now, here are the parts:
- Part 1: Introduction to Functional Programming (you’re here)
- Part 2: Functional Programming Concepts
- Part 3: Introduction to F#
- Part 4: Functions and Delegates in F#
- Part 5: F# standard libraries
- Part 6: OOP in F#
- Part 7: Using LINQ in F# (and the upcoming F# 3.0)
- Part 8: F# Asynchronous workflow
- Part 9: F# MailboxProcessor
- Part 10: Units of Measures
- Part 11: F# Power Pack
- Part 12: F# for Silverlight 4 (and above)
- Part 13: A look at F# 3.0 in VS 11
- Part 14: A look of Functional Programming in VB 10 and C# 4.0 compared to F#
- Part 15: A look of F# compared to Haskell, Scala and Scheme
- Part 16: F# future and what features that F# must have
- Part 17: Retrospective
Part 1: Introduction to Functional Programming
To be honest, many developers especially in Indonesia don’t know much about this. But I bet all of us are already familiar with the concept, at least using it everyday.
But what is really, Functional Programming? Simply put, functional programming is programming with mathematical functions. The longer definition is, programming with emphasize on functions and higher order functions with side effects.
What is a mathematical function? A function in math is an operation that has parameters (1 to many) and return a value. In math, function can be called many times with the same parameter will always yield the same result.
A practical intro to functional programming sample
Let’s dive into math samples, because basic (but fundamental) functional programming is closely connected to math. We are developers, right? then we are all familiar with basic concept of math.
From math to code, it’s fun!
An example of this is the factorial function: (using Piecewise notation)

Using F#, the code above is:

It is similar! Note the rec keyword, it means recursive function “marker”. More on this in Part 4. The “|” character in the sample above means pattern matching in F# (and also in ML family languages).
Another example is this notation of absolute (ABS) function: (again, using Piecewise notation)

We all know that any value of x either positive or negative will return a positive of x, with the condition and operation as above.
For example:
|-6| = 6
and
|6|= 6
No matter how many times you call it, it will always return the same result. But we are more familiar with abbreviated function such as abs(x). Because you will find it’s easier to write in code, either Java, C++, C#, or Visual Basic using abs(x) instead of |x| because you will get syntax errors.
Then we can write:

Now, the function is easier to read and ready to implement on your code.
But since this blog entry emphasize on F#, this is the teaser code:

.. and the teaser code in VS 2010, with F# interactive window shown:

Now, try to write the above function in C# and VB.NET! And you’ll find that it’s quite noisier:
C#: 
VB.NET: 
Yes, C# and VB don’t have match expression, such as those in F#. But this match expression lays out the foundation of today’s modern functional programming languages, such as F# and other ML variants, including other non ML such as Haskell.
In fact, the F# code looks natural to the piecewise notation of absolute value above. And it has very succinct syntax. The term succinct syntax means less noise compared to the other languages such as C# and VB above.
But VB is more reasoned toward functional programming: the return type of the function is inferred from the operation inside of the function body, instead of C#! It’s closer to F#. Also it’s a clear definition in VB to distinguish function and procedure: function returns a value, procedure doesn’t return value and it is meant to do something that can have side effects.
So, a functional programming language is simply programming with math function.
As simple as:
f(x) = y
and y can be a form of an operations such as:
y = x + 1
To maintain consistency and guaranteed that the result will not change, the parameter of the function must be immutable, as seen in the above sample. This is different in C#, VB and others, where you can modify the value of the function parameter.
so, this expression is invalid:
x = x + 1
Why? Because there’s no x equals to x + 1 in math!
In functional programming, this expression:
y = x + 1
is really an equality notation. The equal sign means assigning an operation or value to a symbol, such as y. Therefore x is left unchanged.
Then why is this necessary? Not just this immutability, but there are other concepts as well. It’s way more older than most of us!
But why do I say, we already use it everyday? I’ll explain it later after the “why”.
A short history of functional programming
Based on this functional programming entry on Wikipedia, a functional programming was born from early work on calculus, especially Lambda calculus. Lambda calculus describes functions and their evaluations, including bindings and composition. Although it’s merely an abstraction, it’s definitely a baseline/foundation in modern functional programming.
Sidenote:
C# and VB since Visual Studio 2008 (hence C# 3.0 and VB 9.0, respectively) has embedded this lambda calculus concept and wrapped it up as a nice lambda expression. F# has this since F# 1.0 back in 2005, when it was a research project in Microsoft Research. More on this on Part 13.
An early precursor of functional programming is Lisp in 1958. It has very succinct syntax, and it’s very close to F# syntax today. An example of Lisp:

There’s no return statement, the result is implied, just like F#.
Also notice the indentation. This indentation style is then will be widely used not just in Lisp and F#, but it’s also found in Scala.
Sidenote on LISP:
For more formal standard documentation, see http://www.clisp.org/ for ANSI LISP (also called Common Lisp). Lisp itself has been further researched and there is a derivative work of Lisp called Scheme. Yes, Scheme is another member of functional programming language family.
Lisp has been an inspiration for creations of other functional programming languages, not just Scheme. It’s also being used in other bigger software and more specific such as in AutoCAD began from AutoCAD 9 until now (called AutoLISP).
Further inspiration of Lisp is another variance of functional programming languages, ML (metalanguage) is born in early 1970s. Although it’s originally stated to investigate math theorem of LSF, it was then further researched and then implemented into Caml.

Caml (Categorical Abstract Machine Language) was developed continuously by INRIA, with helps from other large companies in a Caml Consortium. It has more implementations derivations, into OCaml. OCaml adds object oriented constructs to Caml, this is why OCaml is abbreviated from Objective Caml.
OCaml sample: (one of OCaml IDE is Eclipse Indigo (a.k.a. Eclipse 3.7) with OCaml support as plugin)

Looks similar in F#? Yes, absolutely. This OCaml is the known source of inspiration of F#.
There’s a long history about ML, Caml and others but the big picture of this ML family language is this:

For more information about other languages in the picture above, visit http://en.wikipedia.org/wiki/OCaml and from there you will also find some links to other derivatives such as Miranda, created by David Turner in 1983 when he was working at Research Software Limited.

Miranda is also borrowing concepts from SASL (also from David Turner).
This development of Miranda has resulted in new creation of other functional programming language such as Haskell. And Haskell brings a concept of purely functional programming into practice, along with the side effect handling (this side effect is common in imperative programming such as Java, C#, VB.NET) and other concepts in lambda calculus.
But Miranda was also known for its neat implementation of lazy evaluation (also called non strict evaluation for the technique used to minimize repeated evaluations during runtime). This non-strict trait later influenced Haskell and made into OCaml.

Haskell has very interesting history. At first it was mainly used only in academic practice in 1990, now it’s been in use in a larger and commercial user base. Previously considered impractical for general purpose programming, but now it’s matured and it has very large documentation and support base.
Haskell is also the most pure functional programming language that made itself available on various platforms, not just UNIX and Linux. It’s available on Windows too, and Simon Peyton Jones has been porting Haskell to .NET, although currently it only supports Visual Studio 2005 and Visual Studio 2008.
Now, I have mentioned side effects, pure functional, immutabilities, pattern matching.. What are these?
Yes, those are functional programming concepts! Next part 2 is the concepts of those.
Further Reference links
List of further reference links:
- Microsoft F# on Microsoft Research, http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/
- Microsoft Visual F# on MSDN: http://fsharp.net
- CAML official page on INRIA, http://caml.inria.fr/index.en.html
- OCaIDE, OCaml IDE support for Eclipse Helios and Indigo: http://www.algo-prog.info/ocaide/index.php
- Miranda official page: http://miranda.org.uk/
- Haskell official landing page: http://haskell.org/
Hi there! Now that Visual Studio 2010 is almost here, here are some facts about and what's new in Visual Studio 2010.
As you may have known, some of other INDC bloggers have blogged things about VS 2010, and there is a nice prize of blogging competition on this topic. As for me, I just want to tell new interesting facts about VS 2010 especially in Beta 2 release :).
This topic is divided into these series:
- First looks of Visual Studio 2010 Beta 2 (you're here)
- .NET 4 Beta 2 and the related C# 4.0 and VB 10
- New language into Visual Studio: F#
- WPF of .NET 4 Beta 2
- ASP.NET 4
- Team development of Visual Studio 2010 Beta 2
- Extending VS 2010 Beta 2
(... and more to come!)
Now, here's the first:
First looks of Visual Studio 2010 Beta 2
Note: For those didn't have Visual Studio 2010 Beta 2, you can download it from this MSDN portal of Visual Studio: http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx
Visual Studio 2010 comes in different editions, and it’s different in editions than in versions before 2010.
Visual Studio 2008 comes in these flavors:
- Express Edition (free to download and use, but you’ll have to install VB, Visual C#, Visual C++ and Visual Web Developer separately)
- Standard Edition
- Professional Edition
- Team System Developer and Database Edition included (it was initially in a separate edition)
- Team System Architect
- Team System Test
- Team Suite, a you can have it all edition that include Team System Developer, Database, Architect, and Test edition
Quite many, right? Now, for Visual Studio 2010 editions:
- Express Edition (free and the it is the same as Visual Studio 2008 Express)
- Professional Edition
- Premium Edition (this includes features from Team System Developer and Database)
- Ultimate edition (just like Team Suite of VS 2008, but with additional Architect tools and many more)
At first, after you install the Visual Studio 2010 Beta 2, you’ll see this screen: (I use 1024 x 768 resolution)
At first, you’ll notice that it has new first page! Also the Visual Studio logo is also new, although it’s still a Möbius strip, but with a nice touchy bluish theme. But one nice interesting fact is (although you can’t see this directly), Visual Studio 2010 UI is largely developed using WPF 4!
Too bad I can’t use Snoop at first on Visual Studio 2010 running instances to prove this, but you can fix Snoop directly in the code using this tips.
I also downloaded the most “complete” edition of VS 2010, the Ultimate edition. It seems Microsoft wants to sync with Windows Vista and Windows 7 editions, right?
If you select “New Project…” on the right side of the Start Page, you’ll see these project types:
There you are! You’ll see F# dubbed as Visual F# in the list of templates!
And you’ll also see lots of other new template items, such as Silverlight 3 items.
And what about the documentation? It’s not like the previous version of MSDN Library. Visual Studio 2010 has MS Help 3.0, and it’s quite different from the previous versions of MS Help.
You have to install the documentation first by “adding” it to the Help collections as a “local content”.
At first, go to menu “Help” and choose “Manage Help Setting”:
Visual Studio will then check existing configuration of MS Help 3.0 for quite some time, then a Help Manager window will come up:
Choose find content on disk:
Browse to the installation disk and go to “ProductDocumentation” folder and you’ll find:
Select the file, and then add the packages. If you have successfully added the collections restart Visual Studio soon. Go to the Manage Help Settings and you’ll see this:
Now, back to Visual Studio again. Choose menu Help then “Visual Studio Documentation”. A new browser window will pop up and it will also display the homepage of VS 2010 help:
As you see, instead of displaying the MS Help Viewer, the documentation will be displayed directly on a web browser. This is quite useful, since it takes less amount of time and memory compared to previous versions.
But this collections that shipped with VS 2010 Beta 2 is not complete, there will be a bunch of pages or links missing/broken. So, always keep the installation of MSDN Library for VS 2008 SP1, don’t uninstall it.
Now, you’re ready to code! Next: .NET 4 Beta 2 and the related C# 4.0 and VB 10…

Hi guys! Just to refresh my entries about web 2.0 on this intro and then part 2, one of the hype of web 2.0 is semantic web. Now, this semantic is not just talking about the what your page will look, but it’s also what your html (or xhtml) page should be constructed. Meaning that, the source of your web page should be in a context of semantically correct.
Note:
First of all, I’m not a web standards fanatic or advocate! Even though I was once part of the W3C HTML/WG invited participant about 9 years ago.
A very nice example of this is the source of stackoverflow and the most complete sample that I’ve known of, is the website of Tantek Çelik, former Microsoft’s developer of IE 5 for Mac (which is sadly, not further developed).
As we move further and further to XHTML and Semantic Web, the old tags of HTML 3.2 will be considered obsolete or deprecated. W3C itself is moving to more semantically direction.
Web are moving to.. semantic web as semantic in simple linguistic?
Why?
HTML 3.2 and before is:
- A mixes of style and data/content presentation
- Ambiguous tree representation of DOM 1
- Vendor influential (not neutral), for example: APPLET element
- Focusing on quick deployment of looks and layout instantly (remember FONT element?)
- Focusing on “tag”, not element. This is because it’s rooted back to the original hyperlink text created by CERN, the original birthplace of web and HTML and no DOM at that time.
HTML 4.01 is:
- Promoting separation of style and layout (moved into CSS) and content presentation. No FONT element anymore!
- Focusing on HTML element that’s further sync with DOM’s object.
- Less ambiguous and in sync with DOM 2, although some ambiguities are still exist. Samples of ambiguities removed: use DIV instead of LAYER, BLINK is completely removed.
- More neutral and based on very lengthy process of WD-“WD Last Call”-CR-PR-REC that unfortunately can take very long time to wait for finished Recommendation and can be pushed back to WD! Even Microsoft has been struggling with standardization and actively participating since the release of IE 7 Beta (see notes below).
- A natural transition toward stricter DOM and readable and understandable HTML (geared toward browsers for sight impaired/disabilities), even on the source code level, since your HTML can also be read using a combined implementations of WCAI AAA
- This natural transition is bringing more focus on content presentation but still allow STYLEs elements
- Not just have to be understood, the meaning of translated or read HTML has to be meaningful in a sense of semantic linguistic, and therefore semantically correct, not just syntactically valid/correct.
Notes on Microsoft on W3C:
As a result of overwhelming request of IE’s standard conformances, many web developers were leaving IE, even fewer after the release of IE 7. As a matter of fact, IE 8 Beta 2 hasn’t been able to pass ACID2 test.
But Microsoft, especially Microsoft’s employee aren’t just bringing promises. See these promises and “horror” comments of this blog of Chris Wilson, Microsoft IE’s Architect. Also don’t forget to catch up with Chris Wilson’s new blog: cwilso.com.
Curious about latest IE development? Follow IE development on MSDN’s IE Team blog.
XHTML 1.0 is:
- Based on XML 1.0 (now in 5th edition), Namespaces in XML 1.0
- Although a transitional DTD is available, the use of case sensitivity is strongly applied since it’s XML based.
- Can be extended implicitly, although this fact is still debated. But due to the fact of “X” factor in XML is eXtensible, this will welcome new possibilities of applications with other XML related standards at W3C, such as XSL, XSLT, XPath, XForm, XFrame, and others.
- Promoting discipline over readable and transportable web
- Focus on more well formed XML and more correct semantic
Where is the semantic factor, actually?
There are way too many aspects of semantic web and I can’t simply put those all in this small blog entry. But I can give you quick samples.
On the HTML side:
| Element | Semantic HTML | Why |
| <b> | <strong> | More emphasized and clearer definition. It’s also stated in HTML 4.0, this will be rendered as bold face. |
| <i> | <em> | More emphasized and cleaner definition. It’s also stated in HTML 4.0, this will be rendered in italic face. |
| <font> | no longer used | Use CSS to specify type faces and sizes. Also promote more separation. |
| <blockquote> for quotation | <q> for quotation | Cleaner definition over quote of “q”. There have been numerous disagreements on blockquote on many forums of W3C, since blockquote is not clear and ambiguous. |
On the HTML table representation:
- Table should be used exclusively for tabular data, not for HTML layout
- Use thead to give table header a real semantic representation of a header of tabular data, and use tbody for data itself.
- Use fixed width to ease layout calculation for browser rendering, but do this in CSS, not in the HTML source! Hint: use “table-layout: fixed”
- If you need footer or last row summary, use tfoot
- You want caption? You can use “caption” and use it directly as a child element of the table
This is the sample of a table:
<table>
<thead>
<tr><td>First name</td><td>Last Name</td><td>City</td></tr>
</thead>
<tbody>
<tr>
<td>Eriawan</td>
<td>Kusumawardhono</td>
<td>Surabaya</td>
</tr>
<tr>
<td>Benyamin</td>
<td>Suaib</td>
<td>Jakarta</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total data:</td>
<td> </td>
<td>2</td>
</tr>
</tfoot>
</table>
With additional formatting, the table will be rendered like this:
If you look closely, the IE I use is IE 8 Beta 2. See the compatibilty button. :)
These are the complete code of the sample:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Semantic web</title>
<style type="text/css">
thead
{
background-color: #00f;
color: #fff;
}
</style>
</head>
<body>
<h1>Table sample</h1>
<table border="1" cellspacing="0">
<thead>
<tr><td>First name</td><td>Last Name</td><td>City</td></tr>
</thead>
<tbody>
<tr>
<td>Eriawan</td>
<td>Kusumawardhono</td>
<td>Surabaya</td>
</tr>
<tr>
<td>Benyamin</td>
<td>Suaib</td>
<td>Jakarta</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total data:</td>
<td> </td>
<td>2</td>
</tr>
</tfoot>
</table>
</body>
</html>
Are there any help from tools/utilities?
The sad fact is, not many HTML/XHTML editors are aware about these.
Adobe Dreamweaver CS2 and CS3, for example, have acknowledged most of these and it also validates XHTML 1.0 well, but there’s no support for directly inserting thead and tfoot. Dreamweaver CS2 and CS3 also have supports for suggesting the use of “alt” attributes on “img”. Sweet!
I’d like to test Dreamweaver CS4, but the hardware requirements are quite overkill.
Microsoft Expression Web is more lightweight than Dreamweaver CS3, but unfortunately has many XHTML validation consistencies.
Surprisingly, HTML editor of Microsoft Visual Web Developer (of Visual Studio 2008) has valid validation and has “preview mode” that is closer to the current browser used. And it fully respects W3C XHTML 1.0 DTD, not paying respect to IE’s HTML DTD! Although, the suggestion is somehow less cleaner than in Dreamweaver CS2/CS3. Why?
Because Microsoft acknowledges the fact that IE even IE 8 Beta 2 doesn’t explicitly support XHTML 1.0. Only Opera 9.5 (or above), and Firefox 4.0 (yes, 4.0!) support XHTML.
What to see in the near future? I’ll try to continue this humble mumble of semantic web.
Comments are welcome! :)

Funny, now the Windows Live applications and services seem to be in one version sync: version 14.
Get the full standalone of 110MB here:
http://download.microsoft.com/download/7/6/E/76EE3260-D212-4D9B-B8D6-79C014B0593B/EN/wlsetup-all.exe
So, what really is this hefty one package? It contains:
- Windows Live Writer Beta
- Windows Live Messenger
- Windows Live Mail Beta
- Windows Live Toolbar Beta
- Windows Live Photo Gallery Beta
- .. and this strange for me, Windows Live Call Beta. I think it's Microsoft's answer to Skype.
… And they all have the same version: version 14.
Here’s the snapshots:
Windows Live Messenger 14:
Windows Live Writer 14:
Windows Live Mail 14
If some of you may ask, why do I show Windows XP? I need to inform you that you can still install these damn useful applications on Windows XP SP2, and on Vista of course. I suggest, on Vista though. You already have .NET 2.0 on Vista with added twists of security and reliability. :)
Funny or maybe not finished? The Windows Live Writer editor doesn’t recognize the CSS of my blog. Hope they will fix this.
Ah, by the way, Windows Live Writer needs .NET 2.0 runtime. And if you don’t have it, it’s already included in the standalone installer. Enjoy!
I know, it's quite old but it's still relevant, even today in the world of .NET 2.0, 3.0, and 3.5.
What the C or C++ Programmer Needs to Know About C# and the .NET Framework
Enjoy reading! :)
Yes. Why do I say many cares? Just a day after I wrote my latest blog entry about the first silent scream, some of my colleagues gave me supports, including many of my colleagues from Indonesian OMG BMI members. Wow! They even offer me many samples of syllables from many Australian universities, for comparison resources.
Some of them were willing to pour some real cash to accelerate this. But not so fast, though. We need to form a specific "organization", since then it's not an initiative from RX Communica anymore. Basically, they agreed. It's also being considered as a non-profit organization, and there should be no hidden agenda at all, no dependency or dominance from a single company.
Ahh, it may sound easy to say than to really form it. At the same time, while my friends and I are still considering many options, those guys that interested in funding approach me. But, they have to agree on stricter term, especially on these fine prints: "non profit, no dependency and dominance". Few of them backed off.
Funny thing is, some of them thought that we were building a promising startup, just like the story behind the fever of startup on the dusk of web 2.0 bubbles.
Simple answer is: No. We are not building a startup. We're not tied as a promising newcomer for many VCs. Yes, we're concerning about software development in general, and our main target is preparing young talents to be aware of the latest software development theory and best practices, also giving them experiences on real projects.
A first, the base camp is on RX Communica. Later when the need (and also funding) are sufficient, we'll have our own base, since we've agreed about no dominance, even for RX Communica and also my friend's company. We don't know yet the name. :)
Many thanks for you guys, especially from Indonesian OMG guys and my silent scream fellows on Kalimantan. Next, since this topic is no longer about .NET, I'll migrate it to a new host, or maybe I'll use any other free blog services for this time being. Or, do any of you, this blog's loyal visitors, want me to report it here? I will, if you want to. But I'm afraid it'll be less .NET content. :)
As Aerosmith sung:
"It's amazing! With a blink of an eye, we finally see the light..."
Again, many thanks.
Update:
May 147h, 2008: revisiting local type inference and more clarification on VB and C# feature comparison
Close view of Lambda Expressions and the journey to LINQ
Now, what's really a lambda?
According to MSDN Library that comes with VS 2008, a lambda expression is "an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types." That's a mouthful description.
First, an anonymous function. Function, in a sense of C# and VB.NET, is simply a method that returns any value. In VB, it's more verbose, it uses keyword Function. It can be seen as a further development of anonymous method, only it's more like syntactic sugar, since it's more expressive.
Before enjoying this journey, C#3.0 and VB 9.0 new features are not LINQ alone. Many new features of C#3.0 and VB 9.0 forms (or compose) LINQ.
These are:
- Query expression (or query comprehension)
- Local variable type inference
- Lambda expression
- Anonymous types
- Object initializers
- Expression tree
Now grab your popcorn, relax and stay sit. :)
Before Lambda expressions, and others, there has been impedance mismatch of data and object
Now, let's see... The roadmap to the query expression of LINQ. Yes, the journey behind it. You can also see the movie about it on LANGNET 2008 website in Talks section. But for those prefer to seek another way to crunch this concept, let me enlighten you. :)
It all starter when these things happened: "impedance mismatch of objects and relational data".
Or, easily put by Anders Hejlsberg and others:
relationaldata != object
Remember XBase family software such as dBASE, FoxBase (then FoxPro and then Visual FoxPro and then "gone")? Yes, they were neat, if you need to access data, it's so simple. You got the feeling that the data was there, integrated with your language you're coding. It's also giving you compile time errors on query (although there were no such thing like Intellisense). They were also fun to use, since you're concerning only on "what" data you want to display, instead of concerning "how". And the database world has grown not just simple query, but it's grown into a standard based SQL, at least ANSI SQL-92.
The separation grew larger, since the difference was more obvious:
- Database is relational, object is hierarchical,
- Database has nullable types, object didn't have it.
- Database has indexes, primary keys, object didn't have it. But this was solved by major ORM, including #1 above, but not #2.
The long road to marry data and object
Luckily, in CLR 2.0 (also C# 2.0 and VB 8.0) we have Nullable value type, which can be simply written int? in C# or Integer? in VB. Now, we know then, at least in .NET 2.0, we have matched types from database domain.
What about query in our programming language? It's simply can't match the power of the domain specific language such as SQL. Yet, we still need to work at the heart of our general programming language discipline first, the object itself.
The journey of those thinkers in Microsoft is illustrated below.
Suppose I want to query an arbitrary collection in .NET, and later I want to make it "fluent" and looks like query I used to know. Why? Because basically a table is a collection of rows, and this collection can be a CLR IEnumerable<T>.
Now, let's do a simple query of available processes on my machine, and then print it on console.
In C# 2.0:
IEnumerable<Process> processess = Process.GetProcesses();
foreach (Process proc in processess)
{ Console.WriteLine(proc.ProcessName);
}
Console.ReadLine();
In VB 8.0:
Dim processes As IEnumerable(Of Process) = Process.GetProcesses()
For Each proc As Process In processes
Console.WriteLine(proc.ProcessName)
Next
Console.ReadLine()
Oh, what about if I want to know which processes on my machine have size > 50MB? Sure I could add if statement that filter the proc in Processes before I display, like these:
in C# 2.0:
IEnumerable<Process> processess = Process.GetProcesses();
foreach (Process proc in processess)
{ if (proc.WorkingSet64 > (50 * 1024 * 1024))
Console.WriteLine(proc.ProcessName);
}
Console.ReadLine();
in VB 8.0:
Dim processes As IEnumerable(Of Process) = Process.GetProcesses()
For Each proc As Process In processes
If proc.WorkingSet64 > (50 * 1024 * 1024) Then
Console.WriteLine(proc.ProcessName)
End If
Next
Console.ReadLine()
But, this is the query that I want. A query is not like these. I decide to implement Where as a method. But how do I pass expression to be later evaluated and spawned as iterators? Fortunately, C# 2.0 has a new keyword of C# "yield" to have the compiler generates iterators. But sadly enough, VB 8.0 doesn't have it. But you can code it in C# and use it in VB anyway.
Note: This is where the language features of C# and VB seems having unfair advantages: the yield keyword is only available on C#. Why doesn't MS include this in VB? I can't find the reason anywhere, even on MSDN.
After I think for a while, I decide I have to put these into a method with accept generic. Ah, this is a suitable implementation for .NET 2.0 anonymous generic delegate. I think I want a class that contains method that can be called anywhere, and this is definitely a static class.
So, I modified my code to add this class, let's just call it Query. And the method to filter, let's just call it Where. It's perfectly suited for our intent: to filter out elements/items and make new collection with filtered items.
But first, I have to make declaration/definition of the delegate:
public delegate TResult Func<T,TResult>(T arg);
And now, here's the resulting Query class with Where method in C# 2.0:
namespace TrialLINQinNET20
{ public delegate TResult Func<T,TResult>(T arg);
public static class Query
{ public static IEnumerable<T> Where<T>(IEnumerable<T> items,Func<T,bool> predicate)
{ foreach (T item in items)
{ if (predicate(item))
yield return item;
}
}
}
}
Now, my query somehow looks nicer:
In C# 2.0:
IEnumerable<Process> processess = Process.GetProcesses();
IEnumerable<Process> listproc = Query.Where(processess,
delegate(Process p) { return p.WorkingSet64 > (50 * 1024 * 1024); });foreach (Process proc in processess)
{ Console.WriteLine(proc.ProcessName);
}
Console.ReadLine();
In VB 8.0, I can't. It simply doesn't support anonymous functions, and this including anonymous delegate.
Note: This is another aspect of VB 8.0 having unfair advantages: the anonymous delegate/function is only available on C# 2.0. Another "why doesn't MS include this in VB". But in VB 9.0 it's being done as a lambda expression in a more verbose way.
Now, I have created filter or "map" in functional programming terms. I passed the predicate as expressed in delegate.
To tell you the truth, I copy the declaration of Func<T,TResult> delegate from MSDN Library.
What about Select? If you look at the base theory of SQL, it's called a projection. As a matter of fact, projection, filter, and others are essentially part of relational algebra. And it's fun to know that it's part of set theory, which we had in elementary school. :)
Now, let's create a select method. Basically, it projects a collection of type into other collection of type. It can be the same, but it can be different. It looks almost like Where, but I have to change and modify the signature of select method to be able to map IEnumerable<T> to another type.
This is the select method:
public static IEnumerable<U> Select<T, U>(IEnumerable<T> source, Func<T, U> selector)
{ foreach (T var in source)
{ yield return selector(var);
}
}
Yes. Now, if I want to display (and select) only the ProcessName of the running process that has taken more than 50MB of my precious RAM, the code will be:
IEnumerable<Process> processess = Process.GetProcesses();
IEnumerable<Process> listproc = Query.Where(processess,
delegate(Process p) { return p.WorkingSet64 > (50 * 1024 * 1024); });
IEnumerable<String> procnames = Query.Select<Process, String>(listproc,
delegate(Process p) { return p.ProcessName; });foreach (String procname in procnames)
{ Console.WriteLine(procname);
}
Console.ReadLine();
Now... I see the class and the code is simpler to be read. I can map a collection of Process into a collection of String, since I only need to dump the ProcessName.
Please note the sequence here: I need to filter it first, then map it. If I map first and then filter it, I'll loose some information about the data (type metadata) in the collection. So where comes before select! This is different from SQL, since SQL permits select first and then filter it, and then take from a pool of data. In OOP, we have to know from what data we want to use, filter it, and then map it.
SQL seems to cook up structural type before "from" was taken place.
Local type inference revisited...
Hmm... This is somehow satisfactory, but it's full of syntactical noises, where I have to type full type declaration, especially if I have to type long type declaration of generics.
The variable's type on the left side of declaration is already known after I initialized or have been assigned with a value.
Now this is where I begin to use C# 3.0, .NET 3.5, and Visual Studio 2008, since it can infer the type of local variable. Only, it means available only on local variable of method scope. This is why it's simply named "local type inference".
Instead of writing this:
in C# 2.0:
Dictionary<String, List<Int32>> integerdict = new Dictionary<string, List<int>>();
in VB 8.0 it's somehow shorter:
Dim integerdict As New Dictionary(Of String, List(Of Integer))()
And C# 3.0 brings you:
var integerdict = new Dictionary<string, List<int>>();
Again, it means give integerdict the type of the right hand assignment or expression has. It's neat, and it's simpler.
It's still statically typed, since by then the type of integerdict is always Dictionary<string, List<int>>. Yes, it looks like dynamic language, but it's not dynamically typed, and it's not the same as Variant in VB or object in Javascript.
Now, in C# 3.0, my little query class and its implementation is:
var processess = Process.GetProcesses();
var listproc = Query.Where(processess,
delegate(Process p) { return p.WorkingSet64 > (50 * 1024 * 1024); });var procnames = Query.Select<Process, String>(listproc,
delegate(Process p) { return p.ProcessName; });foreach (String procname in procnames)
{ Console.WriteLine(procname);
}
Console.ReadLine();
Pretty neat, isn't it? But this is not query. In real query, I just can combine Where and Select. So, the procnames is a select of filtered data of process.WorkingSet64 > 50MB. How do I do this?
Then I decide to just passing the where to my projection:
var processess = Process.GetProcesses();
var procnames = Query.
Select<Process, String>(Query.Where(processess,
delegate(Process p) { return p.WorkingSet64 > (50 * 1024 * 1024); }), delegate(Process p) { return p.ProcessName; });foreach (String procname in procnames)
{ Console.WriteLine(procname);
}
Console.ReadLine();
But now it looks confusing. In reality, I should filter it first and then map it. Do where first, and then select it. The execution order is correct, but I can't just make it into a sequences.
I was thinking about extending IEnumerable to be able to do query, something like IQuery but it has to be concrete class, not an interface. But then again, it's not so practical.
But I think it would be nice to have this notion: procname.Where(...).Select(...) instead of having to combine Select and Where just like above. In programming buzzword, this way of thinking is called "fluent", since the data/value passed flows like fluid, although it's still to be arranged in a sequence.
Simple sample of fluent thinking:
String name="Eriawan ";
String upperstring = name.ToUpper().Trim();
See? The string is passed. Now, it's more fluid.
Ahhh, it's "fluent" now
Luckily, there's this feature: method extension in C# 3.0 and VB 9.0. I can just "extend" existing class especially "locked" class or classes which has modifier of sealed in C# or NotInheritable in VB.
How to do this?
In C# 3.0:
- Create static class with static methods, with the first parameter is the type you want to add method.
- Put "this" keyword in the first parameter of the static method
In VB 9.0:
- Create new module
- Create method (either Sub or Function) with Public modifier and give the method <Extension()> attribute
And you're on!
So, my Query class in C# 3.0 would be:
public static class Query
{ public static IEnumerable<T> Where<T>(this IEnumerable<T> items, Func<T, bool> predicate)
{ foreach (T item in items)
{ if (predicate(item))
yield return item;
}
}
public static IEnumerable<U> Select<T, U>(this IEnumerable<T> source, Func<T, U> selector)
{ foreach (T item in source)
{ yield return selector(item);
}
//return source;
}
}
Now, the implementations will be:
var processess = Process.GetProcesses();
var procnames = processess
.Where(delegate(Process p) { return p.WorkingSet64 > (50 * 1024 * 1024); }) .Select(delegate(Process p) { return p.ProcessName; });foreach (String procname in procnames)
{ Console.WriteLine(procname);
}
Console.ReadLine();
Yayy! It's more fluent! But... I think it's still noisy. Just look at the delegate syntax on Where and Select. It's simply a function with a parameter and an expression. I want to be more expressive.
Now is the close view of Lambda
Now, this is where Lambda Expression comes to help. Lambda expression, as Norman said in commenting blog entry :), is just basically writing inline function. Lambda expression is just a simple synonym of Lambda Calculus, which is one of the basic of functional programming.
Let's just go down to transform our delegate parameters above, into these:
var procnames = processess
.Where((Process p) => { return p.WorkingSet64 > (50 * 1024 * 1024); }) .Select((Process p) => { return p.ProcessName; });
The fat arrow "=>" is "goes to". It can be simplified as inline function that has parameter p and then "p -> p.ProcessName".
Thanks to local type inference, the lambda parameter type can be omitted:
var procnames = processess
.Where((p) => { return p.WorkingSet64 > (50 * 1024 * 1024); }) .Select((p) => { return p.ProcessName; });
If the parameter is just one, the parentheses () can be omitted too. Also, since the return value is just a simple expression, I can just make it more expressive and looks more functional instead of writing an imperative return statement.
Now the code above looks like this:
var procnames = processess
.Where(p => p.WorkingSet64 > (50 * 1024 * 1024))
.Select(p => p.ProcessName);
Now, the noises are gone. My code looks functional!
But it's still not the query I used to be, I know it's closer. It would be nice to have select and where as keywords, and be integrated into our code.
Now, C# 3.0 and VB 9.0 include this new feature: query comprehension.
Query that is so integrated into our code: Query comprehension
The code before now is transformed using this query comprehension into:
var procnames = from p in processess
where p.WorkingSet64 > (50 * 1024 * 1024)
select p.ProcessName;
and in VB 9.0:
Dim procnames = From p As Process In Process.GetProcesses() _
Where p.WorkingSet64 > (50 * 1024 * 1024) _
Select p.ProcessName
But the LINQ wave doesn't stop here! There are many other discrete cool features in C# 3.0 and VB 9.0 that forms LINQ.
(to be continued...)
I was in the middle of downloading screencast from Channel9 of MSDN and also finishing my part 2 blog.
To my surprise, the 3G connection went so fast! Many thanks to my XL 3G for this connection:
Before this, I always complained to them about how slow it was.
But right after that, I test the real speed using intel bandwidth test:
It looks like I only have a quick surge of 3G speed. Well.. For this speed, it's still slower thean my ISDN connection at home. But, anyway, it's fun to test the real speed. Also, maybe I should sample more test.
I have tested it again many times, and this is what I got an average of 72kbps out of 5 times testing:
So, what I got is a quick surge of 3G speed. Has any of you experienced this phenomenon too?
Yeah. I know. It's quite noisy, either in INDC's mailing list, or in many web that says cool features in VS 2008.
But let me straighthen up first, why I choose LINQ first? It's because becoming hot buzzwords number one. And it can get many wrong views.
UPDATE:
27th March, 2008: fixing typos, code samples are now in C# 3.0 and VB 9.0, not just C# 3.0.
LINQ views and what comes in a single query of LINQ
Ah. Language INtegrated Query. Everyone has been becoming crowded and many shouting at me, "I know it! Of course I know!" But many don't know, it's not just a new essential features of VS 2008, but it's more like one of new features of .NET 3.5.
I also often heard many mumbles that said, "LINQ is the only way","LINQ is the newest concept from Microsoft's family of programming languages", blah, blah, blah, and many leads to almost false altruism.
It can be a sad fact for us but it's true, LINQ is not all that new! In "C Omega", or Cω, the notion that you can include SQL query such as Select is already available before C# 3.0. The name itself is new. Yes, the term LINQ is new, but the concept behind it it's not new. But why I say, not all? The concept of bringing Lambda expressions to LINQ queries are new. I'll try to explain it after this LINQ views.
LINQ it's not exclusive of .NET 3.5, though. Because it's simply a set of new language features capabilities that built into the fabric of C# 3.0 and VB 9.0 language specifications in terms of new keywords and new syntaxes. Most of all, it's simply a syntactic sugar, to ease all of us writing codes especially when dealing with SQL query language syntaxes. And don't forget one thing, .NET 3.5 is still .NET 2.0 lies beneath. So, .NET 3.5 was built on top of .NET 2.0 added with .NET 3.0. It's not exclusive, right?
Since LINQ is not exclusive of .NET 3.5, it's also implied that you can still can do your hard work in doing querying data. Still, you can do many things in ".NET 2.0 ways". But we, as software developers, tend to be more productive, and can be we're obligated to be always more productive and also more innovative in doing our core responsibilities, solving business problems and coding.
So, I strongly suggest that you use LINQ if you have Visual Studio 2008, and please upgrade to VS 2008 if you have 2005 since your new learning curve is not that new. Why? I'm not a strong opponent of using LINQ. In fact, I (again) strongly suggest you to use LINQ as appropriate and wisely for your development. It's helpful. It's not a must, but it eases our coding, and also promoting easier to read and then to code (can be the other way around).
Why? Because you'll get compile time checking and Intellisense in your query syntaxes! This means less error, more focus to the query logic. Also another why is, it's a way to compose pieces of arcane nested select queries, which can have many side effects. This concept comes from functional programming, and later I'll explain this after LINQ stuffs.
But be prepared to dive the concept behind LINQ uses first. You have to know it. I strongly suiggest you to learn it also. There are some facets of many programming paradigm "hidden" from us!
A quick LINQ to SQL
First, easier to code. Why? Let me give you a basic example of LINQ querying a LINQ to SQL (formerly DLINQ)generated class that represents Customers, from our good old sample database of Northwind (it's not installled by default in SQL Server 2005, you can get it here).
These are quick step by step to get your feet wet quickly:
In this sample, I create a LINQ to SQL classes and name it Northwind.dbml
Now let's use this new classes, but please pay attention that you have to understand what really is "LINQ to SQL Classes" is.
Basically LINQ to SQL is a quick "one stop shopping ORM" tool that maps your SQL Server database, tables, relations, and also stored procedures into hierarchical objects and CLR methods.
Your database will be mapped into a DataContext, your table will be mapped to
Just add these tables from Northwind to the Northwind.dbml:
- Customer
- Order
- Order_Detail
Just for fun, add the SalesByCategory stored procedure into Northwind.dbml and you'll see this:
Now... it's quite straightforward, right? But, where's the real LINQ?
Ah, LINQ is not pictures and models. This tool simply helps us visualize this code: (in the Northwind.designer.cs)
These are the code that represents Northwind database (also conceptually):
public partial class NorthwindDataContext : System.Data.Linq.DataContext
{
private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
#region Extensibility Method Definitions
partial void OnCreated();
partial void InsertCustomer(Customer instance);
partial void UpdateCustomer(Customer instance);
partial void DeleteCustomer(Customer instance);
partial void InsertOrder(Order instance);
partial void UpdateOrder(Order instance);
partial void DeleteOrder(Order instance);
partial void InsertOrder_Detail(Order_Detail instance);
partial void UpdateOrder_Detail(Order_Detail instance);
partial void DeleteOrder_Detail(Order_Detail instance);
#endregion
public NorthwindDataContext() :
base(global::WinFormDLinq.Properties.Settings.Default.NORTHWNDConnectionString, mappingSource)
{
OnCreated();
}
public NorthwindDataContext(string connection) :
base(connection, mappingSource)
{
OnCreated();
}
public NorthwindDataContext(System.Data.IDbConnection connection) :
base(connection, mappingSource)
{
OnCreated();
}
public NorthwindDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public NorthwindDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public System.Data.Linq.Table<Customer> Customers
{
get
{
return this.GetTable<Customer>();
}
}
public System.Data.Linq.Table<Order> Orders
{
get
{
return this.GetTable<Order>();
}
}
public System.Data.Linq.Table<Order_Detail> Order_Details
{
get
{
return this.GetTable<Order_Detail>();
}
}
[Function(Name="dbo.SalesByCategory")]
public ISingleResult<SalesByCategoryResult> SalesByCategory([Parameter(Name="CategoryName", DbType="NVarChar(15)")] string categoryName, [Parameter(Name="OrdYear", DbType="NVarChar(4)")] string ordYear)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), categoryName, ordYear);
return ((ISingleResult<SalesByCategoryResult>)(result.ReturnValue));
}
}
In VB:
Again, quite straightforward, eh?
The rest of the code is the declaration of tables.
Now, again, where's the LINQ, or query, or the code thingy?
I simply use the NorthwindDataContext and create a new instance of it. Then, just get Customer table from it! With a hint from Intellisense. Yes.
Okay! Now the LINQ!
In this quick sample, I dump the output of the LINQ to SQL of Customer to an IEnumerable and then put it as a DataSource of a Windows Forms GridView:
in C#:
private void Form1_Load(object sender, EventArgs e)
{
NorthwindDataContext dbnorth = new NorthwindDataContext();
var qry = from c in dbnorth.Customers
select new { c.CustomerID, c.ContactName, c.CompanyName, c.City };
this.dgvCustomer.DataSource = qry;
}
In VB:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim dbnorth As NorthwindDataContext = New NorthwindDataContext
Dim qry = From c In dbnorth.Customers _
Select c.CustomerID, c.ContactName, c.CompanyName, c.City
Me.dgvCustomer.DataSource = qry
End Sub
Run it, you'll get the same column results from the select query above:

What if I want to filter it? Hmm... Let's just say I want to get data of customers in London.
Change the code above to this:
In C#:
private void Form1_Load(object sender, EventArgs e)
{
NorthwindDataContext dbnorth = new NorthwindDataContext();
var qry = from c in dbnorth.Customers
where c.City == "London"
select new { c.CustomerID, c.ContactName, c.CompanyName, c.City };
this.dgvCustomer.DataSource = qry;
}
In VB:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim dbnorth As NorthwindDataContext = New NorthwindDataContext
Dim qry = From c In dbnorth.Customers _
Where c.City = "London" _
Select c.CustomerID, c.ContactName, c.CompanyName, c.City
Me.dgvCustomer.DataSource = qry
End Sub
you'll get this:
Voila!
More productive, right? I just create this sample code less than 5 minutes!
As you see, the "select" is now keyword. So is "where" and "from". But from comes before select, which is different from the original SQL query of SELECT.
Why? Because SQL language is not quite natural in the way the ordinary compiler process. You can't put the "select" first, since you have to know from what kind of set of data you want to manipulate or to select.
The quick notion is: I have to know from what set of data I want to select, then select it. Not the way that SELECT SQL works. Because compiler can't know at first the variables you want to select if you don't define from what data first. Now, enter the world of Declarative Programming!
Why? Because you think what you want to, not how it can be done. Declarative programming is everywhere, from WPF's XAML, to XML Schema, and to quite old domain specific language such as Prolog and our old data centric language (and also domain specific language), SQL query.
Quite funny, isn't it? You've used SQL but you didn't know what kind of taxonomy SQL query was.
But don't be happy soon, C# is not entirely Declarative Programming. It's an imperative programming family member, same as VB.NET.
See? This is why I told you up front, you have to know some concept first. And the depth doesn't stop here. Let's see how the code above is translated into, and I call it, "first phase". But before that, enter another new cool features of C# 3.0 and VB 9.0: type inferencing.
Type inferencing
See this:
var qry = from c in dbnorth.Customers
where c.City == "London"
select new { c.CustomerID, c.ContactName, c.CompanyName, c.City };
You may wonder, is it still type safe? Variable qry has no type defined up front! If you debug and hover your cursor to qry variable, you'll get IEnumerable. Actually, the code above says, "give variable qry the type of the right hand expression has". So, qry has the type of IEnumerable.
I can also create this variable x as Int32 using type inferencing:
var x = 1;
It's using var and it functions the same as Dim in VB. VB also have it. But var looks like Javascript, and Javascript is dynamic language family member. Enter the world of dynamic language!
But, again, it's up to you to decide whether this is a good or bad news, since C# is not purely dynamic language. For me this fact can be understood perfectly, because C# is intended strongly typed at first, unlike Javascript.
Now, the query code above is translated into this first phase:
var qry = dbnorth.Customers
.Where(c => c.City == "London")
.Select(c => new { c.CustomerID, c.ContactName, c.CompanyName, c.City });
Or in VB:
Dim qry = dbnorth.Customers _
.Where(Function(c) c.City = "London") _
.Select(Function(c) New With {c.CustomerID, c.ContactName, c.CompanyName, c.City})
Have you seen this syntax above before? The "c=>"?
In C#3.0 and VB 9.0, it is called Lambda Expressions. But VB is not taking the same syntax, it's written as new Function which is then translated into Lambda function. VB programmer prefers syntax that's more verbose.
The idea of Lambda Expression itself was taken from a topic of Lambda Calculus, from mathematic foundation. We now turn our journey to the world of exotic Lambda Calculus, but only as an overview in C# or VB view. Now, we're now walking towards new world of Lambda Calculus.
Lambda Calculus (or Lambda Expression in C# 3.0 and VB 9.0)
Now, what is Lambda calculus anyway? It is simply a functional view of expressing your code. But in a deep glass magnifier view, it's a formal system (as in Wikipedia) to investigate function applications and recursion.
In C# and VB, it's a functional way to express delegate and expression tree types.
(To be continued..)
Yes. It is. I feel dizzy again thinking about what are our youngster wannabe geek doing and thinking today, either they're still studying or being graduated.
I'd experienced many things during my quite long (more than 1 month) silence period. I was doing my coding partially outside Java, the Kalimantan island, while also helping my friends there. My friends are IT lecturers (focusing on software development concepts) from quite a reputable state university and also teaching at other private university as well. Not to mention they have a small software company (call it "micro ISV", just like mine) that sells web solution based on ASP.NET 2.0.
Unspoken yet proven local heroes
Note: I won't mention their company name in here. Also they asked me not to tell their names. But you'll find it on IBM's GSSG website, and they're one of a very rare IBM software development premier partner in Indonesia while also having IBM Rational certifications and MCP certifications in .NET.
I was eager to know many things about educations, especially education IT on Kalimantan. Yes, mostly people of Kalimantan have a warm welcome, comparing to Surabaya. But, I was shocked after visiting and helping them to interview candidates for software developers. Before, they told me, "Don't expect much from fresh graduate locals and from Java graduates." Huh? What's up? They told me that I shouldn't expect graduates to be a good junior software developer to pick.
At first, I didn't believe it. There is should be at least one. Can't find just one? This is impossible.
The truth is more an irony than just a sad fact.
It took almost a week to interview about 30 candidates, but I can only help them for 2 days. Although it's already advertised "looking for C# developer", almost 30% of submitted applicants were failed; they didn't know C# and basic OOP as well.
The rest 70% was quite good at first. They knew basic C# 2.0 and .NET 2.0 concepts, including generics, delegates, using statement (as a deterministic object scope), and collections. But, little they know concepts of .NET CLR. There were fruitful debates at that time, between my friends and me. Finally they agreed to include design pattern and common coding best practices as a requirement. But again, they warned me, "You'll lose many candidates. We won't include that requirement now." Please take note about the word "lose". Lose here doesn't mean that they'll lose good candidates after applying, lose here they'll lose candidates before applying after seeing the fact and yet they mumbled, "What? Design patterns? best practices? no. I don't have that in university".
Ironies
Other ironies comes in again after I met one of candidates at lunch and I was pretending to apply. He told me that most lecturers in his university always giving him doctrines about the best programming language, best OS, and also focusing to learn many programming languages instead of nurturing students to solving business problems, understanding the very basic software development concepts such as DBMS, SDLCs (such as waterfall, iterative, UP), programming paradigms (e.g. imperative programming, functional programming, declarative programming) and many more. He also told me that if he wants to propose .NET 3.0 study as its topic of his final assignment, he'll be out of luck. The majority of his lecturers have rejected him for many non sense reasons such as "We don't use that. What is WPF? No need to learn new things! Just stick to your study and get graduated fast!"
Other candidate that also had lunch with me told me that they somehow got used to think that every concept they've learned from their past universities were enough. No. It's not enough. I calmly told and explained to him that what he'd learned mostly were not conceptual at all. I was having quite painful conversation, since he at first was defensive. After a long persuasion, he realized that he had to learn many basic things that makes a real concepts.
After I discussed this with my friends, they told me that those reasons simply translated to: "I don't know that. Since I don't know WPF and even .NET 3.0 and I won't learn new things since I don't have to. So you as a student simply get back to your chair and just finish your damn study just like others!"
D'uh. I also remembered this bad mentality experience while I was consult my final assignment about 10 years ago. Now still happens.
Heroes and silent screamers
What about my friends as a lecturers? They have gone from "loud scream" to "silent scream". They were known as many bright lecturers and also post graduate students (all of them have at least masters in software engineering and one PhD). Yes, now they're not known from the outside world. But they've been struggling at the university senate level to insert and also assert basic software development concepts while at the same time facing the fact that most of their own colleagues (lecturers, deans) are not willing to shift from programming-language-mastering to instead of conceptual algorithm thinker and problem solver paradigm. They're also always teaching and evangelizing students about the use of best practices, design patterns, and many more. Another best thing: they defend students that have good software developer potentials and have enormous passions of continuous learning and improvements.
Openly against that? Not a chance, they said. Many useless arguments and reasons have been thrown at them. Not to mention threats in form of discipline sanctions because of having against the (bad) habits that have been working for so many years without complaints from students and alumnis.
It's a very fond of them, since my friends love to teach, share, and discuss many things especially about advantages in .NET, software development, and modeling. This is why they're also have quite heroic choices to keep struggling to educate others. Although they don't get paid well by their current universities. They should.
My heart was breaking and I've decided to help them personally and also having helps from friends under my company umbrella, RX Communica.
My proposal to my friends are:
- Giving additional trainings and workshop about those concepts outside their universities
- Giving free ebooks such as project Otak as one of first means to accelerate learning programming in Indonesian language while also articulating and exercising other programming paradigms
- Incubating and sharing some software projects (including their own and jointly developed with RX Communica) to be developed by their potential students
- Continuously giving constructive critics and suggestion at higher education levels while also giving encouragement to see and understand wider perspective of software developments for almamaters, fellow lecturers, especially IT related lecturers
Closing
What about us? You? Do we care about those who now screaming in silence? Especially for those who keep low profiles and have done many things to make their surroundings and students better.
I do believe we all care. We do care. And by the way, do we have guts to scream in silence in our own local surroundings and our own almamater also? Thanks to them, I do have it now. :)
But I believe we can construct a constructive and intelligent ways to handle this, instead of directly criticize them and hitting their academic pride. Gandhi has proven as one of the best silent screamers. Many other also.
Have any suggestions? Please. you're more than welcome. :)
Yes, what a shame. I'm too late submitting it (here's my participations on project otak). Many thanks to Agus Kurniawan, for his patience to always reminding me. Also I welcome critics, suggestions, and rants.
Now, I've come home from finishing jobs outside island of Java. I'm ready to participate again in this blog, emails, mailing list.
Guys, please forgive me for my prolonged silence.
More Posts
Next page »