Learning F# – Part 2

Disclaimer: I do not claim credit for the code examples and much of the contents here, these are mostly extracts from the book by Chris Smith, Programming F#: A comprehensive guide for writing simple code to solve complex problems. In fact, if you’re thinking of learning F# and like what you read here, you should buy the book yourself, it’s easy to read and the author has gone go great lengths to keep things simple and included a lot of code examples for you to try out yourself.

Primitive Types

F# is statically typed, meaning that type checking is done at compile time.

F# supports the full set of primitive .Net types which are built into the F# language and separate from user-defined types.

Here’s a table of all the numeric types (both integer and floating-point) with their suffixes:

image

F# also allows you to specify values in hexadecimal (base 16), octal (base 8 ) or binary (base 2) using prefix 0x, 0o, or 0b:

clip_image001

There are no implicit type conversion in F#, which eliminates subtle bugs introduced by implicit type conversion as can be found in other languages.

Arithmetic Operators

You can use standard arithmetic operators on numeric primitives, like other CLR-based languages, integer division rounds down to the next lowest number discarding the remainder. Here’s a table of all supported operators:

image

A very important to note here is that by default, these arithmetic operators do not check for overflow! If a number becomes too big for its type it’ll overflow to be negative, and vice versa:

clip_image002

F# also features all the standard math functions, here’s a table of the common math functions:

image

BigInt

If you are dealing with data larger than 2^64, F# has the BigInt type for representing arbitrarily large integers. While the BigInt type is simply an alias for the System.Numerics.BigInteger type, it’s worth noting that neither C# nor VB.Net has syntax to support arbitrarily large integers.

BigInt uses the I suffix for literals, see example below:

clip_image003

You should remember that although BigInt is heavily optimized, it is still much slower than using the primitive integer types.

Bitwise Operations

Primitive integer types support bitwise operators for manipulating values at a binary level:

image

Characters

The .Net platform is based on Unicode, so characters are represented using 2-byte UTF-16 characters. To define a character value, you can put any Unicode character in single quotes, for example:

clip_image004

Like C#, to represent special control characters you need to use an escape sequence from the table below:

image

You can get the byte value of a character literal by adding a B suffix:

clip_image005

Strings

String literals are defined by enclosing a series of characters in double quotes which can span multiple lines. To access a character from within a string, use the indexer syntax, .[ ], and pass in a zero-based character index. For example:

clip_image006

If you want to specify a long string, you can break it up across multiple lines using a single backslash, \, for example:

clip_image007

Like in C#, you can define a verbatim string using the @ symbol, which ignores any escape sequence characters:

clip_image008

Boolean Values

F# has the bool type (System.Boolean) as well as standard Boolean operators listed below:

image

F# uses short-circuit evaluation when evaluating Boolean expressions, meaning that if a result can be determined after evaluating the first of the two expressions, the second value won’t be evaluated. For example:

true || f() – will evaluate to true without executing function f.

false && g() – will evaluate to false without executing function g.

Comparison and Equality

You can compare numeric values using standard operators listed below:

image

All these operators evaluate to a Boolean value except the compare function which returns -1, 0, or 1 depending on whether the first parameter is less than, equal to, or greater than the second.

You should have noticed that these operators are similar to those found in SQL Server and F# doesn’t distinguish assignment from equality (like C#, where = is assignment and == is equality comparison).

When it comes to equality, as in other CLR-based languages, it can mean different things – value equality or referential equality. For value types, equality means the values are identical. For reference types, equality is determined by overriding the System.Object method Equals.

Learning F# – Part 1

I decided to take some time out on Silverlight and have a play around with Microsoft’s new language F#, I’ll be making notes as I go along and post them here so maybe they’d help satisfy some of your curiosity too!

Disclaimer: I do not claim credit for the code examples and much of the contents here, these are mostly extracts from the book by Chris Smith, Programming F#: A comprehensive guide for writing simple code to solve complex problems. In fact, if you’re thinking of learning F# and like what you read here, you should buy the book yourself, it’s easy to read and the author has gone go great lengths to keep things simple and included a lot of code examples for you to try out yourself.

Before you start, you need to download F# from:

http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/release.aspx

and install it for either VS2008 or VS2010 beta.

Hello, World

In VS2008, open a new project and choose F# Application, in Program.fs type in:

printfn “Hello, World”

Hit Ctrl+F5, and voila:

You might notice that your program worked without an explicit Main method.

Here’s a slightly more complex Hello, World to show off the syntax of F#:

image

The let keyword binds a name to a value, unlike most other programming languages, in F#, values are immutable by default (meaning they cannot be changed once initialized).

image

F# is also case-sensitive. The name of a variable can contain letters, numbers, underscore, or apostrophe (‘) and must begin with a letter or an underscore. However, you can enclose the value’s name with a pair of tickmarks in which case the name can contain any character except for tabs and newline:

let “this.Isn’t %A% good value Name$!#“ = DateTime.Now.ToString(“hh:mm tt”)

printfn “%s, %s at %s” greeting thing “this.Isn’t %A% good value Name$!#“

Other languages like C# use semicolons and curly braces to indicate when statements and blocks of code are complete, but it clutters the code.

In F#, whitespace (spaces and newlines) is significant. The F# compiler allows you to use whitespace to delimit code blocks. For example, anything indented more than the if keyword is considered to be in the body of the if statement. Because tab characters can indicate an unknown number of space characters, they are prohibited in F# code. You can configure the Visual Studio editor to automatically convert tab characters into spaces in Tools -> Options -> Text Editor -> F#.

The earlier code also demonstrated how F# can interoperate with existing .Net libraries:

let timeOfDay = DateTime.Now.ToString(“hh:mm tt”)

F# can take advantage of any .Net library by calling directly into it, conversely any code written in F# can be consumed by other .Net languages.

Comments

Like any language, F# allows you to comment your code. To declare a single line comment, use two slashes (//).

For larger comments that span multiple lines, you can use the multiline comments using (* and *) characters.

For F# applications written in Visual Studio, there is a third type of comments: an XML documentation comment. If a comment starting with three slashes (///) is placed above an identifier, Visual Studio will display the comment’s text when you hover over it:

 


F# Interactive

Visual Studio comes with a tool called F# Interactive or FSI. F# Interactive is a tool known as a REPL (read-evaluate-print loop), it accepts F# code, compiles and executes it, then prints the results. This allows you to quickly and easily experiment with F# code similar to how snippet editor allows you to do the same with C# code.

Once it’s open, it accepts F# code until you terminate the input with ;; and a newline, the code entered will be compiled and executed. After each code snippet is sent to FSI, for every name introduced you will see val <name> : type value, for example:

Notice when you don’t give a variable a name, FSI will simply call it ‘it‘.

FSI allows you to write code in Visual Studio editor which offers syntax highlighting and IntelliSense, but test your code in the FSI window. You can copy the entire code body from the example earlier and test the main method in FSI by calling it:

Managing F# Source Files

The F# language has some unique characteristics when it comes to managing projects with multiple source files. In F#, the order in which code files are compiled is significant.

You can only call into functions and classes defined earlier in the code file or in a separate code file compiled before the file where the function or class is used. If you rearrange the order of the source files, your program may no longer build!

The reason for this significance in compilation order is type inference, a topic to be covered later on.

F# source files are compiled in the order they are displayed in Visual Studio’s Solution Explorer, from top to bottom. You can rearrange the files by right-clicking and selecting Move Up or Move Down. The equivalent keyboard shortcuts are Alt+Up and Alt+Down, though these don’t seem to be working in VS2008 with Resharper, or maybe I just need to tweak my key mapping.

Buzzword Buster – AOP

Definition:

Aspect Oriented Programming (AOP) is a programming paradigm where each application can focus on its primary functions and core concerns by encouraging greater modularity and increasing separation of cross-cutting concerns (such as logging and authentication).

Purpose:

In any real-world applications, when you’re writing code to address the problem domain (say, booking an order) you might need to address other concerns such as:

  • persistence – writing to the database for example
  • transaction handling – defining transaction scope and setting rollback strategy, etc.
  • security – user authentication for example
  • logging – for auditing and debugging

So effectively you’re mixing multiple domains with fine-grained intersections and likely to end up with:

  • tangled code – making it more difficult to work out what the code is doing to address the core concern
  • boilerplate code at every intersection point – introducing duplicated code and increasing the size of the code base and the blast radius of any change that are not related to the problem domain, e.g. changing the persistence media..

AOP aims to address these problems by separating cross-cutting concerns into single units called aspects, each aspect encapsulates behaviours that affect multiple classes into reusable modules.

Parting thoughts..

As far as I can think of, the only drawback of AOP is that you no longer see all the behaviours of your class when you open it and it requires knowledge of the whole system to know what else are happening under the cover. Which interestingly, is the flip side of the same coin because you employ AOP when you don’t want to deal with cross-cutting concerns all the time!

One of the ways to mitigate this problem is to build up a culture in your team and standardise how AOP is implemented so that everyone is on the same page and there are few surprises.

Frameworks:

PostSharp provides a lightweight AOP framework for the .Net platform and is establishing itself as the de facto standard much like the way AspectJ has done for Java.

Good old days!

My good friend Raj sent me some pictures he took from Chinese new year 2006, and really brought back some nice memories from the days gone by!

As some of you may know, I performed on stage for Chinese new year in 2006 in Trafalgar Square, in the middle of the freezing cold in Feb! It was definitely one of the best experiences I ever had, the adrenalin rush of performing in front of thousands of people was simply amazing! So, to show you what I’m on about, here’s some pictures ;-)

63_430x330 CNY%20290106%20-%20%2814%29

CNY%20290106%20-%20%2820%29 DSC00032

DSC00033 DSC00036

100_0163030406 (2)

and don’t we all love a poser lol

100_0167

Adoption problems with WPF

I was having an email conversation with a friend on WPF yesterday and he suggested putting it into a blog post after I went on and on for a bit (sorry Raj!).

Having spent some time learning Silverlight (which is a subset of WPF for the web, Microsoft’s equivalent of Flash) I have really come to like the new programming model in WPF and how easily it allows you to do things that were simply impossible to do in WinForms (ever tried to put a rounded corner to a rectangle anyone?).

To those not familiar with WPF, it’s powered by DirectX so you get hardware acceleration and can use features such as transparency, gradients and transformations. Its programming model enables clear separation of the UI from business logics because you now have to build your UI using a declarative language – XAML (Extensible Application Markup Language).

The event model has also been revamped and it’s now possible to ‘route’ an event so it originates from one element but is raised by another. WPF supports several types of routed events, but Silverlight only allows bubbled events which cascades up the containment hierarchy from deeply nested element to its containers.

Why is Declarative UI better?

Whilst declarative UI is something of a shock to the system to most of us (web developers not included!) it actually makes perfect sense because it helps solve one of the biggest problems in UI development – business logic embedded in UI.

A declarative UI makes it harder to write business logic into the UI because you’re writing less code. However, it’s not about separation of tiers, but separation of concerns, so when you find problems there is a smaller blast radius! Which again, all comes down to loose coupling – the same thing people are trying to achieve with IoC and Dependency Inversion from a dependency point of view.

So all’s well with WPF and industry veterans are all raving about it (there’s a number of shows on DotNetRocks alone which covers WPF and Declarative UI) so why is there still a distinct lack of real-world apps out there? Besides the odd project on CodePlex like Family Show and Scott Hanselman’s BabySmash, I haven’t found too many examples out there (it’s a shame Photology‘s dead.. :-( )

Problems:

I think there are two main reasons why a lot of people are still not adopting WPF, neither has anything to do with the technology itself which is like a fancy new drug which makes you never want to go back! And there are plenty of industry support both in terms of third party support (well known UI controls producers like teleriks, infragistics already offer numerous UI packages for WPF and Silverlight) and backing from the industry veterans.

1. it’s still fairly young

Having only made it into the core .Net platform since .Net 3.0 (nov 2006) it is still fairly new to most developers considering that most people are still happy using .Net 2.0 (I know this is definitely true in the banking/enterprise world!) which equates to:

  • a lack of existing expertise in the field, making it hard for would-be adopters because it adds to the cost of adoption in time and expense regardless of their strategy to acquire these expertise, i.e. new recruit vs. training existing staffs
  • an additional risk with adopting WPF because you have to first migrate your platform to .Net 3.0, which, should be minimal because it’s really just an add-on to the .Net 2.0 framework. But then again, “why fix what’s not broken?”

2. it’s only a viable option for new developments

Because WPF introduces a completely new set of technologies and a new programming model to boot, it’ll require significant time and effort to convert an existing UI application. This means WPF is only worth considering for new developments.

The future:

As with all things Microsoft, there’s a strong focus on enterprise users and I’m sure their representatives would continue to make a push for their partners to adopt WPF and dare I say once they decide to jump on board MS would have a problem stopping them from coming back for more! Yup, WPF is that good!

With the .Net platform going strong as ever (mentioned in 44% of developer jobs posted in the UK in the last 6 months), the universal adoption of WPF as the de facto standard for developing UI application should only be a matter of time. Given the risk-adverse nature of large enterprises (who, given their size and financial muscles, have more say on technology trends than anyone else), it’s no surprise to me that WPF has not really caught on, but as more and more enterprises jump on the WPF bandwagon they’ll in turn increase the size of the talent pool available to others and really set the ball rolling.

Further reading:

WindowsClient.Net

Prism: patterns & practices Composite Application Guidance for WPF and Silverlight site