Archive for the Category Uncategorized

 
 

Some Notes on the C# to F# Posts

Two quick notes about the three posts so far:

1. I posted a RFC about this series on Reddit. Some of the comments are pretty interesting, it may make sense to read it. In particular masklinn has posted a comment about my “definition” of the term currying, to which gmarceau had a reply. I have no idea who is right as I don’t really care too much about exact definitions, but if you do you might want to do some Googling of your own.

2. roy_hu has commented on my explanation about the reasons for the rec keyword. The explanation in the link he provided doesn’t seem 100% correct to me, but I never wrote a type inference algorithm so there’s a good possibility that I’m wrong.

From C# to F# – Part 3

Although my last post leaves me with a bunch of things that deserve further explanation and further spelunking through the F# type system, the first order of the day is to make your knowledge of F# Turing-Complete so that you can start writing simple programs. And to do that you need to know how to write loops, which leads us to immutability.

By default variables in F# are immutable. Once you declare them you can’t change their value. So while in C# it’s perfectly normal to write:

var x = 1;
...
x++;

in F# there is no equivalent construct.

(All right, all right, I’m lying, F# also supports mutable variables. But using them is considered dirty. F# programmers, when forced to use mutable variables for performance reasons probably end up in the shower frantically scrubbing themselves while sobbing “I feel so dirty, I feel so dirty.”)

In fact they don’t even call them variables. They call them values, to further emphasize the fact that they don’t change, and to differentiate themselves from unwashed masses that use programming languages that don’t have theoretical underpinnings in lambda calculus.

The fact that variables are immutable has two advantages: one, the programs tend to look a lot like mathematical expressions which theoretically makes them easier to reason about; and two, they are easer to parallelize because the type system guarantees that there are no side-effects.

But there’s a problem. Without the famous i++ you cannot write loops. No loops and you can’t write an arbitrary program.

Fortunately, F# supports recursion, and recursion is as good as loops. For example, to write a function that prints “Hello World” ten times in a row, you could first write the following helper function and use it instead of a loop:

let rec loop n f =
    if n > 0 then
        f ()
        loop (n - 1) f

let helloWorld () = Console.WriteLine "Hello, World!"

let _ =
    loop 10 helloWorld
    ignore (Console.ReadLine ())

The first function, loop, is dead simple. It takes a number n and a function f (void –> void, or unit –> unit in F# parlance), and if n is greater than zero calls f and then calls itself recursively with (n – 1) and f.

However, it introduces two new concepts. The first is that instead of writing:

let loop = something

we wrote:

let rec loop = something

The rec keyword tells the F# compiler that loop is a recursive function so that the compiler should be aware of the identifier loop when evaluating the function body.

Compilers in other languages don’t need a special keyword for recursive function declarations, so why the weird syntax? The keyword is there to prevent you from making unintentional errors. Remember, F# uses the let keyword for both function and variable definitions. And even in languages like C# saying:

var n = n + 1

is an error.

But since F# doesn’t really know if you are defining a function or a variable, it plays it safe and forces you to declare that a function is recursive.

The second concept we just introduced is the if-then expression. F# basically has three forms of the if statement:

1. if <condition> then <expression that evaluates to unit/void>

2. if <condition> then <expression1> else <expression2>. This behaves like the C# ?: operator, returning the value of expression1 if the condition is true and expression2 if it’s false.

3. if <condition1> then <expression1> elif <condition2> then <expression2> … else <expressionN>. This is just a more general form of if-else for cascading ifs.

The next function we have written is helloWorld. The only thing weird about it is the () after its name. Why do we need that? Why not simply write:

let helloWorld = Console.WriteLine "Hello, World!"

without the parenthesis at the end? We certainly didn’t have to use any parentheses when declaring the add function at the start of this tutorial.

Well, this again brings us to the fact that F# uses the let keyword for both functions and values. And since void/unit is a valid variable type in F#, in this particular case if we omit the parentheses the compiler would interpret it as roughly the following C# code:

void helloWorld = Console.WriteLine (“Hello, World!”);

In C# this immediately looks weird because void is not a valid type for variables, but if you construct a different example:

let readLine = Console.ReadLine ()

vs.

let readLine () = Console.ReadLine ()

it becomes apparent that the first case is a direct call to Console.ReadLine with the result being stored in the variable readLine, while the second case is the readLine function which, when called, returns the string that the user has entered.

The reason why I’m beating this dead horse so much is because void/unit is weird that way. Usually when you have a function that takes parameters of a different type the compiler can differentiate between a function call and a delegate reference, but for unit you have to force it.

Finally, our main function is simple. It calls the function loop with the number 10 and a delegate to the helloWorld function, and then simply waits for you to press Enter in order to see the result.

At this point you should know enough to start experimenting. You know currying, you know how to write functions, you know how to declare variables, you know how to do ifs and loops, and you know how to call into static members of the .NET Framework classes.

For example, say we want to replace the helloWorld function with a more general function to which you can pass the string to print out. Currying to the rescue:

open System

let rec loop n f =
    if n > 0 then
        f ()
        loop (n - 1) f

let print (text : string) () = Console.WriteLine text

let _ =
    loop 10 (print "Goodbye cruel world.")
    ignore (Console.ReadLine ())

As you can see, we renamed the function helloWorld to print, and added an extra parameter text, for which we unfortunately had to specify the type because Console.WriteLine is overloaded for numerous types so we needed to tell the compiler that the actual type is. Then, in the main function, we combined the delegate print with the string “Goodbye cruel world", thus creating a function of type unit –> unit which we then sent into the function loop.

You now know enough to be dangerous. If you want to learn F#, now is the time to open up Visual Studio and start modifying the code. Maybe write a function that you can use as a for loop. Or modify the above loop function to pass the loop counter into the function f. Or write a factorial function. It’s going to be painful because both the syntax and the concepts are different than C#, but bang your head against the wall, consult Google, write a question in the comments, do anything to write these little programs because they will teach you more about F# than hundreds of books.

Part 4

From C# to F# – Part 2

Last time I posted I explained that F# compiler simply evaluates function calls from left to right. Since that tends to be a sticking point for most people coming from imperative programming languages here’s an under the hood look.

Remember, we had a function that looked like this:

let add x y = x + y

This function is very simple, here is the C# equivalent:

int add (int x, int y) { 
    return x + y; 
}

But the function call is more complex. If you remember, the call was:

let a = add 1 2

Now, the .NET library has the following delegates declared:

delegate TResult Func<TResult> (); 
delegate TResult Func<T, TResult>(T arg); 
delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);

Also, the F# library has the following functions:

Func<T2, TResult> Evaluate<T1 ,T2, TResult> (this Func<T1, T2, TResult> f, T1 arg1) { 
    return arg2 => f (arg1,  arg2); 
} 

TResult Evaluate<T, TResult> (this Func<T, TResult> f, T arg) { 
    return f (arg);
}

So when the compiler reads the line:

let a = add 1 2

it simply reads the function body left to right and strings the Evaluate statements, producing the code that is the equivalent of the following C# code:

var a = new Func<int,int,int> (add).Evaluate(1).Evaluate(2);

(Of course there are optimizations so this case will be compiled to the same straightforward IL as the C# code, but the main point is that at the basic level it’s just an evaluation left-to-right with calls to Evaluate.)

Now here’s the cool thing about F#: You can also call the function add with just one parameter, and it will, as you can see above, produce a new function that takes an additional parameter before returning the result:

let addone = add 1 
let b = addone 2

This property of F# and other functional languages is called currying.

Now currying is mondo cool and you’ll be using it a lot when programming in F#, but it also leads us to an important point about type signatures:

Say you have a function that takes an integer and returns an integer:

let square x = x * x

If you look at the type of the function square (hover over it until the intellisense tooltip pops up), F# will report it as int –> int. That means that it’s a function that takes an integer and produces an integer.

But if you hover over the definition of the function add:

let add x y = x + y

Visual Studio will report the type of add to be int –> int –> int. What the … ?

It’s simple. Even though you think of a function add as a function that takes two integers and returns an integer, the F# compiler interprets it as a function that takes one integer and returns another function that takes one integer and returns an integer.

In other words, the F# compiler views add as int –> (int –> int), but then simply removes the unnecessary parenthesis (1 + (1 + 1) == 1 + 1 + 1) and presents you with the endless string of arrows like this int –> int –> int.

As a C# programmer, you might find it most comfortable to take a soup that looks like this:

int –> double –> string –> bool

and think about it like this:

int, double, string –> bool

e.g. a function that takes an int, a double and a string and returns a bool.

Part 3

From C# to F# – Part 1

I’ve decided to write a short tutorial that teaches F# to a reasonably intelligent C# programmer. The idea is to make it all meat and no fat so that no time is wasted.

I’m writing the samples using Visual Studio 2010 Beta 2. Microsoft has promised that you will be able to upgrade from Beta 2 to the final product without pain (unlike previous versions of Visual Studio where installing a beta could fuck up your computer royally) so I went ahead and installed it this morning.

So, open up VS and create a new F# Console project. Then type the following code:

open System

let add x y =
    x + y

let _ =
    let a = add 1 2
    Console.WriteLine a
    ignore (Console.ReadLine ())

Let’s take a brief look at what we see:

First, notice that there are no semicolons. F#, by default, uses whitespace to determine the structure. Tabs are verboten in source files, and there are no indentation wars (two spaces or four) because how many spaces you need to indent depends on the keyword used in the previous line.

Next, at the top, we have open System. That’s the same thing as saying using System in C#, so that part is easy.

Following that we have the function add, which takes two parameters, x and y, and returns their sum. The function is weird because a) it’s declaration has no parenthesis, b) parameter types and the return type are not specified, and c) there is no return statement even though that’s what’s being returned. Let’s take a look at each of those:

a) No parenthesis. Get used to it, that’s the F# way. Parenthesis in F# are used for precedence operations – 1 * (2 + 3), and to quickly create pairs and tuples – (2, 3) is basically a value of type Pair<int,int>. Finally, F# uses empty parenthesis – () – to denote a parameter of type void. But no parenthesis for function declarations or calls.

b) No types specified. F# uses type inference to figure out the parameter type and the return value for each function. Notice that lower in the code we call add with two integers, 1 and 2, so the compiler will figure out that add takes two integers and based on x + y it will then figure out it also returns an integer.

c) No return statement. Think of F# functions as mathematical functions, e.g., f = x + y, with void being just another thing that a function can return.

After the function add, we have another function, with a weird name _. That’s the main function. Languages in the C family use a special function called main, F# uses _. Just a convention.

Let’s take a look at our main function. Since all the lines inside it are indented the same way, this is a simple sequence of statements that are executed one by one.

The first line:

let a = add 1 2

is a function call to add, with the parameters 1 and 2, with the result stored in a variable called a (it’s not really a variable but a “value”, but we’ll leave that for the next time). Again, no parenthesis in the function call. The reason why there are no parenthesis is that when you write just add, the compiler sees that and basically pushes a delegate to the function add on the stack. That delegate is Func<int,int,int>, familiar to those that use C# 3.0.

Then, after the token add, the compiler sees the value 1 and applies it to the previous value on the stack. So “add 1” basically combines Func<int,int,int> and an integer, and returns a new delegate, this time a Func<int,int>.

Finally, after add 1, which leaves a delegate int –> int on the stack, the compiler sees a 2. It combines the 2 with that delegate, and lo and behold, we have a real function call that is executed and add is called. The result is finally an integer which is assigned to the variable a.

So the basic function call in F# is simply push stuff onto the execution stack from left to right, and evaluate stuff at each step.

The next one is a call to Console.WriteLine with a as the parameter. Console.WriteLine is an Action<object> delegate, which combined with the object a that follows it results in a function call that prints out the value of a.

Finally, we want the program to pause so that you can see the result. So we write Console.ReadLine, but that just pushes the delegate Func<string> to the compiler’s stack. In order to actually call that function we have to pass it a parameter, which is weird since it doesn’t take any parameters. We get out of that bind by adding (), which is a value of type void, which then forces the function call to happen.

But that leaves with one unforeseen problem: Console.ReadLine returns a string, while our main function (_) must return void (“unit” in F# parlance). And remember, the compiler will puke, because everything is more or less a mathematical function, and it will tell you that your main function is trying to return a string instead of void. So in order to pacify it we call the function ignore with whatever Console.ReadLine returns, and the function ignore simply swallows the result and returns void.

Part 2

Some Google Love on CSS

LOL. Prompted by a comment by DDan I searched Google and my post on CSS is the #3 result for “css clusterfuck”.

I don’t really care how people vote with their links, but this one brought a smile to my face.

Unit Tests, Redux

I view unit tests the same way I view Macs. I like them but think that people who talk about them all the time should be punched in the face.

Joel Spolsky’s post about Coders at Work thus brought me a lot of pleasure. I didn’t necessarily agree with him, I just liked the fact that all the loudmouths are going to start screaming unhappily about it.

But now a follow up post by the author of the book delivers an even better kick in the face to the asshats. Where Joel was dismissive Peter is educational. Where Joel rushes to the conclusion, Peter slowly builds the case.

The last part of Peter’s post was somewhat painful to me as it basically demolishes a TDD “guru”. It reminded me about early nineties when I was a similar loudmouth about the virtues of Object-Oriented Programming and C++ and got my ass handed to me.

Enabling PowerShell Remoting

With Windows 7 comes PowerShell 2.0, which supports executing commands on a remote computer. I’d rather have Windows support SSH and single-window RDP, but as this comes built-in I thought I’d give it a whirl.

Getting it set up based on information from the interwebs is hellishly hard. The whole thing works through HTTP and has a somewhat weird security model*, providing a lot of WTFs per minute.

Anywaysy, in the end it turned out to be simple. Open up an admin PowerShell prompt, and type:

PS> Enable-PSRemoting -force
PS> cmd
C:> winrm set winrm/config/client @{TrustedHosts="*"}

Do this on both the client and the server, and you’re good. Then open the PowerShell ISE from the Start menu and chose File –> New Remote PowerShell Tab. Boom.

 

* Yes, I know everything should be locked by default, but it still should be a Pit of Success when you decide to do it. A simple way to create one would have been enabling it by default on the client and enabling it with a single command on the server to support authentication through SRP.

Awesome World War Two Synopsis

Reddit had a link to this short, funny and correct synopsis of the second World War written by Norman D. Landings. This is how history should be taught in schools.

Immutable Collections for .NET

Jared Parsons has a created a library that provides, among other things, immutable collections.

Windows 7 Sensor and Location APIs on the FAIL boat

Reading this post about the Windows 7 interop samples, all I can think is “uh-oh, it’s Indexing Service all over again”.

Microsoft invented all the components for successful desktop search back in the year 2000. But they didn’t think about scenarios, and then Apple came with the same concept done right and got all the accolades. And now with the Sensor and Location APIs, Microsoft is continuing to use their old play book instead of learning and improving.

The following sentence tells it all:

For example, the following image shows an updated version of the MSDN Reader. This version of the MSDN Reader changes the way the application looks depending upon the amount of light the Ambient Light Sensor detects.

Changing the app colors based on the ambient light? Really? Is that the best you can do? Where is your imagination?

Why not make the applications smarter? Fix your fucking Bluetooth stack and drivers and make my computer know if I’m near it based on the location of my phone. The use that to (maybe) lock and unlock my computer, set the sound level for various notifications, and do other things I need.

And use your position to bend the manufacturers’ arms into adding more sensors to their laptops. I want microphone arrays. I want high-quality webcams. I want an RFID tag on my wristwatch. I want my computer and my phone to remind me to take out the trash when leaving the house because they figured out that my Wi-Fi signal is getting weaker.

I know that asking manufacturers to spend those extra $5 on a $2000 computer is tough when most of them don’t even want to spend an extra buck on a backlit keyboard, but without the sensors your sensor API is useless.