Wednesday, January 22, 2014

An adventure journey of Functional Programming and F# in Visual Studio: Part 1 of 17

Hello there!

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

NOTE:

This blog is moved from MUGI blog, with some refinements. Also this blog is starting to use Visual Studio from Visual Studio 2012 and Visual Studio 2013 (from Release Candidate to RTM), and provide hints of F# 3.0 in Visual Studio 2012.

Now, here are the parts:

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

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.

We all know this in math:

y = x +1

and we can simply translate y into function of x:

f(x) = x + 1

So intuitively we can say

f(x) = y = x +1

Therefore distinction between function and data now becoming transparent!  

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)

wikipedia_recursive_factorial_piecewisenotation

Using F#, the code above is:

sample_fsharp_factorial

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) value function: (again, using Piecewise notation)

absolute_value

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:

absolute_function2

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:

introfsharp_vs2010_p0

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

introfsharp_vs2010_p1

Now, try to write the above function in C# and VB.NET! And you’ll find that it’s quite noisier:

C#: introfsharp_vs2010_p2

 

VB.NET: introfsharp_vs2010_p3

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:

introfsharp_vs2010_lispsample1

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_logo

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_images

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)

OcaIDE_eclipse_indigo

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:

ML_hierarchy_fsharp

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_logo

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_2010_logo

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:

  1. Microsoft F# on Microsoft Research, http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/
  2. Microsoft Visual F# on MSDN: http://fsharp.net
  3. CAML official page on INRIA, http://caml.inria.fr/index.en.html
  4. OCaIDE, OCaml IDE support for Eclipse Helios and Indigo: http://www.algo-prog.info/ocaide/index.php
  5. Miranda official page: http://miranda.org.uk/
  6. Haskell official landing page: http://haskell.org/

Wednesday, January 15, 2014

F# with visual IDE support project template is available

Hi all,

Little known to all, there’s a WPF project template that supports F#, with the help of F# type providers! Yes, we can now create WPF app using F# with visual IDE support of XAML!

This handy extension is created by Daniel Mohl, one of Visual F# MVP!

fsharp_wpftemplate_vs

The project template is available as Visual Studio extension for VS 2012 and VS 2013: http://visualstudiogallery.msdn.microsoft.com/e0907c99-bb04-4eb8-9692-9333d5ff4399

Note: it’s also available for VS 2010 but I believe VS 2010 is now nearly at the end of lifecycle. So please VS 2012 at least.

The project template is available under Visual F#->WPF like below:

fsharp_wpfprojecttemplate_createproject_thumb_5C62EAE8

Create it, and now you’ll have WPF visual IDE for F#:

fsharp_wpf_visualide_thumb_7FCF6980

Now F# is becoming more fun to use for WPF developers!

Wednesday, January 8, 2014

TEACHING: Study club of MUGI Jadetabek on Developer Track, WEEK 5

Now, it’s week 5! We could not have the workshop within the next week of week 3 because of my busy schedule, sorry!

In this week 5, we decided again to meet at QQ Kopitiam, at Pacific Place at 10:00AM. This scheduled time was agreed upon us by communicating via email before. Unfortunately Wakhid has to take care of his administrative undergraduate submission paperworks so he couldn't attend this week. And Aris also can’t attend this for personal reason. Next time, please be punctual, guys!

Yup, the show must go! Sorry to leave you if you weren’t present, guys! It’s fortunate for Reza and Siti Smile

Now we already have grabbed the basic concept of generics and colections, now we are moving to LINQ concept but with the introduction of advanced Lambda expression.

Why do we have to know Lambda? Because the answer is quite simple but somehow often missed in many LINQ literature: LINQ is composed by anonymous delegate. This anonymous delegate is often written in functional syntax as Lambda, to emphasize that expressiveness of an anonymous function is available to use and to compose nicely.

Let’s revisit the basic sample of SELECT in LINQ to Object:

using System.Diagnostics;
using System.Linq;

namespace SampleAdvancedLambda
{
    class Program
    {
        static void Main(string[] args)
        {
            var processnames = (from p in Process.GetProcesses()
                                select p.ProcessName).ToList();
        }
    }
}

The code above (in bold) is basically the same as:

var processnames = Process.GetProcesses()
    .Select(p => p.ProcessName).ToList();

 

Again, type inference will infer that processnames is a List of String, the type syntax is List<String>. Type inference happens nicely because the select will infer the property of ProcessName, and this property is typed String.

The notation of “=>” in the Select method is a form of denoting Lambda Expression. Although this is a syntactic sugar, it’s quite powerful syntax to replace tedious one line anonymous delegate.

But, what happened inside a select? Basically this is a select method body: (it has to be inside of a static class)

public static class QueryHelper
{
    public static IEnumerable<U> Select<T,U>(this IEnumerable<T> data, Func<T,U> selector)
    {
        foreach (var item in data)
        {
            yield return selector(item);
        }
    }
}

If you look at the signature, there’s “this” keyword to identify that this is an extension method of IEnumerable<T> (the first parameter).

Looks like they were having a little bit difficulties to grab this concept, here are their expression: Smile

WEEK5_01

 

I also gave them some sample cases, like constructing your own ForEach and ForNext (For Each with index) as Lambda.

And Abdullah is joining force to dive this concept!

WEEK5_02

 

Fortunately, they began to see the light that Lambda Expression is not that hard!

WEEK5_03


Further references:

  1. C# Extension method reference in Visual Studio 2010: http://msdn.microsoft.com/en-us/library/bb383977(v=vs.100).aspx
  2. C# Lambda Expression in Visual Studio 2010: http://msdn.microsoft.com/en-us/library/bb397687(v=vs.100).aspx

Tuesday, December 24, 2013

Season’s surprise: IE 11 for Windows 7 SP1 and Windows Server 2008 R2 SP1 is released

Yes! Previously available for Windows 8.1, now IE 11 is also available for Windows 7 SP1 and Windows Server 2008 R2 SP1.

I recommend you, my blog audience, to download the 64bit version as Microsoft is moving towards 64bit.

In fact, Windows Server 2012 R2 is only available in 64 bit!

This is the download page URI: http://windows.microsoft.com/en-us/internet-explorer/download-ie

Microsoft is also beginning to broadcast IE 11 downloads:

IE11_win7_win2008R2_thumb_7DE74C83

Enjoy full speed browsing in IE 11!

Thursday, December 19, 2013

RX Web Services journal: WCF in .NET 4.0 implicitly fits REST Maturity Model Level 2

Hi my blog readers!

Another journal is born! now RX journal about web services!

I have just dived deep in .NET 4.0 technology stack, when this week I was assigned to create web services. As .NET mostly guy, I revisit my skill in creating WCF.

Outside world, many things happened. The need of having REST services with the correct model and incorporating HTTP verbs (not just GET and POST) is becoming crucial and more relevant.

Fortunately, Leonard Richardson has written the REST maturity model as the baseline for us. But Martin Fowler, the best known guy that one popularized DSL and PoEAA (Patterns of Enterprise Application Architecture) helped us to understand REST maturity model.

Martin Fowler described the levels into these:

  • Level 0 – RAW HTTP
  • Level 1 – Resources (with HTTP binding as endpoints)
  • Level 2 – HTTP verbs
  • Level 3 – Hypermedia

Level 0 means you’re using RAW HTTP with either GET or POST, but the resulting request and response is plain XML. This is why Martin describes this Level as swamp of POX (Plain Old XML). A good sample of this is .NET Remoting using RPC in .NET 2.0 and above and Java’s RMI. In Level 0, the talks only involves talking to only one endpoint.

Richardson-Maturity-Model_Level0

Level 1 means you’re considering the request and response as real HTTP object, but the main concern here is talking and requesting specific resources as part of HTTP conversation.

This picture was taken from Martin Fowler’s article:

Richardson-Maturity-Model_Level1

This means not just specifying endpoint, but we also specify which resources needs to be sent and to have.

Level 2 means incorporating HTTP verbs, meaning that now not only specific resources, but it’s also introducing HTTP verbs with response codes.

Richardson-Maturity-Model_Level2

This means that Level 2 add more concern on separation of which HTTP verbs are changing states and not changing states.

These HTTP verbs change states:

  • POST
  • PUT
  • DELETE

This HTTP verb does not change state:

  • GET

Fortunately, WCF in .NET 4.0 is confirmed to have full support of Level 1 and with more care, it also supports Level 2.

This is a small sample of Level 1: (an operation contract of testvalue)

WCF_REST_simplesample

And this is the explanation related to the REST levels:

WCF_REST_Maturity_Level1_thumb_72DE5E5E

It’s quite simple in WCF, isn’t it? But when you consider Level 2, you also have to pay attention to the verb and the HTTP returning status codes.

Supports for setting and getting HTTP status code is available in WCF using WebOperationContext.

I’ll dive into WCF supports for Level 2 in the next blog entry about this.

Put it simply, Level 2 concerns about:

  • Resource specific (as in Level 1)
  • using HTTP verbs
  • specifying HTTP status codes (for each HTTP verb used) as a mean to define what is the nature of the resulting resource.

Level 3 add concerns about using HTTP as the transport for Hyper media, means that the data will have the additional information of what is the next destination.

It’s quite elegantly illustrated as below picture:

Richardson-Maturity-Model_Level3

As you can see, there’s additional information in the forms of links to the resource. This means that the hyperlinks in the data has to be specified.


Further references

Tuesday, December 10, 2013

TEACHING: Study club of MUGI Jadetabek on Developer Track, WEEK 4

Now, it’s week 4! We could not have the workshop within the next week of week 3 because of my busy schedule, sorry!

Also in the week 4, we decided to meet at QQ Kopitiam, at Pacific Place at 9:30 because I had something to do first in the morning. Not just my schedule, but the study club will need to adjust with the participants. Therefore this week 4 was commenced on 7th December, 2013.

To my surprise, the attendance were few: Wakhid and Aris weren’t present. But Wakhid was able to tell me that he’s still minding his final paper assignment.

Ok, the show must go! Sorry to leave you if you weren’t present, guys!

This week I reviewed the knowledge of basic generic and collection. To my surprise, not all of them understood and grabbed the full concept of last week.

WP_000182_thumb_5D41B33E

The assignment was to create a simple implementation of LINQ’s WHERE and also implement ICollection<T>, so I decided to repeat the explanation on how generic works.

Basically we can consider generic type as parameterized type or type as parameter. So, if we declare ICollection<T>, we could use and implement derived ICollection with String as parameter (or any type).

The type T then can be replaced by String, so the use will be ICollection<String> (read as ICollection of String). In fact, arrays in .NET 2.0 and above are implemented as collections of parameterized type, so when we have array of bytes, it’s actually implemented as collections of strongly typed bytes, not just array of boxed objects.

Sample from MSDN: (from http://msdn.microsoft.com/en-us/library/vstudio/b5bx6xee%28v=vs.110%29.aspx)

// The .NET Framework 1.1 way to create a list:
System.Collections.ArrayList list1 = new System.Collections.ArrayList();
list1.Add(3);
list1.Add(105);

System.Collections.ArrayList list2 = new System.Collections.ArrayList();
list2.Add("It is raining in Redmond.");
list2.Add("It is snowing in the mountains.");

Although it’s very subtle, the ArrayList will cast to objects, and this is called boxing.

As consequences, we also need to understand boxing and unboxing concept in C# and VB. For more info, visit boxing and unboxing in MSDN Library.

Now with .NET 2.0 and above, we can create list with strong typed:

// The .NET Framework 2.0 way to create a list
List<int> list1 = new List<int>();

// No boxing, no casting:
list1.Add(3);

// Compile-time error:  // list1.Add("It is raining in Redmond.");

Now every time we access each or any member of list1, we are confident that the type of the member is int.

This type parameter concept is very powerful, and it’s becoming a basic feature for all modern programming language nowadays. Not just languages on top of .NET platform, .NET itself has integrate generic deeply as part of CLI and CLR implementation.

Other platform such as Java had begun implementation of generic in Java 5 (JDK 1.5.0) although it came late. Luckily, there’s an official tutorial of generics in Java from Oracle.

By integrating generic deeply into the runtime, now it’s up to the programming language to leverage this! In .NET, we have C#, VB, F#, C++.

Hey, it’s time for the participants to try!

WP_000184-2_thumb_71186989

Finally, they could create the LINQ WHERE! …And now time to eat!

WP_000191_thumb_5A38D666

Next meetup: advanced LINQ concept.




Sidenote


Again, I encourage all of you to read TAPL book by Benjamin Pearce, to fully understand the type theory behind generic type.

Thursday, November 28, 2013

Team Foundation Service is now called Visual Studio Online

Hi my blog audiences!

My favorite free Team Foundation Service is now called Visual Studio Online!

This is the original official announcement: http://www.visualstudio.com/en-us/news/2013-nov-13-vso

vs_online

It’s also coincidence with the launch of Visual Studio 2013!

Also we can code using Visual Studio by online using “Monaco” (Microsoft codename):

vs_online_monaco


Monaco will support ASP.NET, Javascript, Ruby, Python and PHP!

Now the pricing for Visual Studio Online is complete:

http://www.visualstudio.com/products/visual-studio-online-overview-vs

The good news is for 5 developer in a team (or less) the price is free. For more than 5 developers, Visual Studio Online is available in subscription levels.

The level is Basic, Professional and Advanced, and here’s the official comparison table:

vs_online_comparison

Now, what are you waiting for? Start code today in a team!