Archive for January, 2009

Define custom operators in F#

I was reading past section 4.1 of the F# spec, Operator Names, when an idea occurred to me: can I define custom operators that have no other ‘normal’ definition? I had seen some stuff in the spec that suggested how one might do this, so I gave it a go. I constructed a nonsense operator: &^^%. Let’s look at the code first:

 

    1 #light

    2 

    3 let (&^^%) x y = x + y

    4 

    5 printfn “%d” (10 &^^% 32)

The output:

42

(Yeah, I’m a Hitchhiker’s Guide fan.) What did we really do? Well, I asked Reflector what it thought it saw. The response in C#:

I see this method:

 

    1 public static int op_AmpHatHatPercent(int x, int y)

    2 {

    3     return (x + y);

    4 }

and I see it being called like so:

 

    1 FastFunc<int, Unit> func = Pervasives.printfn<FastFunc<int, Unit>>(new Format<FastFunc<int, Unit>, TextWriter, Unit, Unit, int>(“%d”));

    2 int num = Program.op_AmpHatHatPercent(10, 0x20);

    3 func.Invoke(num);

What I find interesting is that the compiler has a mechanism to convert the punctuation symbols into a function name. The rest seems kind of sensible/obvious. That is, the solution makes sense. This does bring up a few interesting questions:

  • What is FastFunc?
  • What is Pervasives?

FastFunc has this description in the docs:

The .NET type used to represent F# function values. This type is not typically used directly from F# code, though may be used from other .NET languages.

An instance of FastFunc defines an Invoke method. The type has several static/class members to do an InvokeFast with 3, 4, 5, or 6 parameters.

Pervasives represents the set of functions that are automatically visible in any F# application without making an explicit reference to the Microsoft.FSharp.Core.Pervasives namespace.

Leave a comment

Effective REST Services via .NET Getting Closer

Kenn Scribner and I are busy getting our book, Effective REST Services via .NET, ready for publication. We’ve already written all the content and received the technical reviews. This past weekend, Kenn spent some serious time making sure that the voice in the book was consistent. Today, the editors get there hands on the manuscript in order to fix punctuation and English. That’s right, the folks with degrees in English will fix our prose. It’s exciting to know that this book is getting closer to being on bookshelves and available for ordering from Amazon. Unlike the other .NET REST titles out there, we don’t spend 300+ pages talking about WCF and how cool it is. Instead, this book walks through all the different ways that a .NET developer has created to expose and consume REST services. IHttpModule, MVC, Azure, ADO.NET Data Services, JavaScript, XMLHttpRequest, WinForms, ASP.NET, Silverlight, WPF, and WCF. Depending on what you are doing and the type of service you are consuming, one of these technologies makes more sense than the others. No other book or resource covers the set of mechanisms in this manner. If you develop web applications as a intranet or Internet developer, you will appreciate having this book on your bookshelf. I can’t wait to have my copy!

Leave a comment

F# and Line/File/Directory macros

I learned how to program in C a long time ago (maybe 1992?). When diagnosing issues, I got accustomed to being able to have an exception or other message targeted at a developer to explain where the message came from. I could review the logs an know where the message was printed in the build of the system that the user had running. Using this power, I could get context with an otherwise uninformative message like

got here __FILE__:__LINE__

In 2001, I moved into .NET full time. I got garbage collection, assemblies, reflection, and so much else. I lost __FILE__ and __LINE__. I learned to push out PDBs to get file and line information when I needed it in exceptions. But, I couldn’t push those files out to production. I learned to use SOS with WinDBG and a collection of symbols to debug production issues, and I moved on. As I write this, I’m reading the F# spec. Guess what I saw in section 3.11 of the spec?

The following identifiers are automatically replaced by values in F# code:

__SOURCE_DIRECTORY__ replaced by a literal verbatim string, e.g. C:source
__SOURCE_FILE__ replaced by a literal verbatim string of the filename as given to the command line compiler or on a load line, e.g. sourcefile.fs, after taking into account adjustments from line directives.
__LINE__ replaced by a literal string giving the line number in the source file, after taking into account adjustments from line directives.

Here is an example of printing these values to the console.

 

    1 #light

    2 

    3 printfn “Source Directory: %s”  __SOURCE_DIRECTORY__

    4 printfn “Source File: %s” __SOURCE_FILE__

    5 printfn “Line: %s” __LINE__

The resulting output:

Source Directory: C:UsersScott SeelyDocumentsVisual Studio 2008ProjectsCloudService1TestApp
Source File: C:UsersScott SeelyDocumentsVisual Studio 2008ProjectsCloudService1TestAppProgram.fs
Line: 5

This is too freaking awesome! It is such a simple tool for diagnostics and it does so much. I was worried that the whole exercise in learning F# would really be some form of mental masturbation. So far, I’m seeing some real plusses. I’m also having fun.

Leave a comment

Fun with Azure

I’m still waiting on a Storage and Hosting account with Azure. This kind of bites since I am a member of the Cloud Services Advisory Group– I’d have thought I’d get some preferential treatment, but no. Still, I am using the Windows Azure SDK to build stuff. This means that I can still experiment locally. A little while ago, while checking to see if my F# code would run OK with a cloud service, I ran into a deployment issue. I had the SQL Server Express database installed and had the Development Fabric and Development Storage up and running via VS2008. I pressed F5, Internet Explorer eventually popped up, and I saw

Internet Explorer cannot display the webpage

I then clicked on the Development Fabric, selected the Web Role, and saw this reported in the Web Role window:

Role state Suspended
Role state Started
Role state Stopping
Role state Stopped
Role state Aborted

Also, the ball next to the WebRole was blue instead of green. Blue means bad. (Aside: Is this some sophomoric gag to the team: the role has ‘blue balls’?) Frustrating! I checked that everything was configured correctly and it was. So, I asked my good friend, Google, how to solve the problem. I asked it, http://www.google.com/search?q=. You know what? It only had one answer. Here’s the issue: my home PC uses a username with a space in it. At home, I use full names as user names. Example, I am Scott Seely. This means that my user profile points to C:UsersScott Seely. The files/scripts that the Development Fabric uses do not account for spaces in temp folders, which means me and anyone else who dares put a space in their user name will suffer the same fate. The fix is to start the Development Fabric from an elevated command prompt, started from the Microsoft Service Hosting SDK Command Prompt, found under Start–>All Programs–>Microsoft Service Hosting SDK 1.0.0. Make sure that all copies of dfservice.exe are terminated. With that command prompt up, run this command:

bindevfabricdfservice -sp “C:fabrictemp”

Now, you can run your application on the fabric.

BTW, the F# code runs fine on Azure on my local machine. I still don’t know about the situation when running in the cloud, but I assume it will be no more than adding a few DLLs at most.

Leave a comment

Moved to Sitefinity CMS

You may have noticed a big change to the site. It almost looks nice, right? I started using Sitefinity for the Lake County .NET Users’ Group late last month. I really like the product, so I figured I would go with the community edition for my personal site. From what I’ve seen so far, the code is laid out quite well and is very easy to understand. I’ve made a few minor modifications to the master pages– everything was very intuitive. And, the admin features are first rate. If this site ever starts making money, I’ll be buying a full version– the product is completely worth the price.

Leave a comment

What does #light mean?

If you see any F# code listing, you will see that almost all of them start with the command #light. Right now, this is a requirement. The first line in any F# file must have #light. After reading about the language, I grokked that it allowed for a shorter syntax than the alternative, #light “off”. Here’s what I’ve been able to figure out so far. From Development in a Blink, I see this:

The #light declaration makes whitespace significant. Allowing the developer to omit certain keywords such as in, ;, begin, and end.

For those of you that have used Python, this makes sense. Indentation gets to have meaning when #light is on. Blocks of code are physically aligned, so indicating where something starts and stops is redundant and, potentially, useless. So, what happens when we turn #light off? Let’s take the Name type developed in a recent post. With #light, the class looks like this:

 

#light

 

namespace SomeNamespace

type Name(fname : string) =

    let mutable fName  = fname

    member this.FName with get() = fName

                                    and set(x) = fName <- x

So, what did #light buy us? Well, it meant that we couldn’t write the following, equivalent code:

 

#light “off”

 

namespace SomeNamespace

type Name(fname : string) =

class

let mutable fName  = fname

member this.FName with get() = fName

and set(x) = fName <- x

end

The difference, in case you missed it, is that class and end HAD to be declared. Furthermore, the indentation/whitespace was no longer significant. This let’s me write code that is harder to visually parse. And yes, I could have indented the code to make it more readable:

 

#light “off”

 

namespace SomeNamespace

    type Name(fname : string) =

    class

        let mutable fName  = fname

        member this.FName with get() = fName

            and set(x) = fName <- x

    end

 

I think I’ll be using #light since most examples on the web stick with this syntax. Being the odd man out won’t help me or anyone else who eventually needs to use my code. Good habits start now. #light also let’s me write less code. I have a fairly consistent ratio of lines of code/defects. If I can avoid some little details and lines of code, I will have fewer mistakes.

Leave a comment

Predicting the name of an F# type

One of the first questions I came up with yesterday when digging into F# was this: what does an F# type look like to C#? As a noob, that’s an interesting question to me. Of course, being a noob, I had no clue about how to create a custom type. So, I asked Google what an F# type definition looked like, then massaged that until I had something that I might not completely understand, but that does show the problem at hand. I created a lame Name class that only supports a first name. Boo-yah!

First, I went to an existing file in an F# library called stuff.fs. There, I added the following class:

 

     type Name(fname : string) =

         let mutable fName  = fname

         member this.FName with get() = fName

                                         and set(x) = fName <- x

For you C# heads out there, let’s look at what the code above really is saying.

  • Create a new type, Name.
  • Name has a single constructor that takes a string.
  • Name has a member variable, fName, whose value can change at runtime.
  • Name has a public property, FName, that has a getter and a setter.

OK, so now what does this look like in C#? I add the F# library to a C# project, instantiate a copy of Stuff.Name (I’ll get to the Stuff item in a moment), and then I right click on Stuff.Name and pick Go to Definition. Since we are in C# land, VS 2008 will pull up the C# vision. This looks exactly like the following:

 

using System;

 

public static class Stuff

{

 

    [Serializable]

    public class Name

    {

        public Name(string fname);

 

        public string FName { get; set; }

    }

}

That’s kind of weird. I didn’t expect to see Name declared as a inner class from a static class whose name comes from the name of the F# file. Still, that’s what we have. Does this mean that F# code doesn’t allow one to create CLR namespaces? No– of course not! So, how do you get the Name class into a CLR namespace called SomeNamespace? I did a little digging and found out how:

namespace SomeNamespace

    type Name(fname : string) =

        let mutable fName  = fname

        member this.FName with get() = fName

                                        and set(x) = fName <- x

Yeah– there’s a keyword called namespace that allows you to add objects to a CLR namespace. The odd bit here is that one doesn’t say namespace blah =. Instead, you omit the ‘=’. The ‘=’ will work, but you will get a message saying that the syntax has been deprecated. With this small change in place, things look more correct to my C# eyes. The static class disappears, and that’s good!

 

using System;

 

namespace SomeNamespace

{

    [Serializable]

    public class Name

    {

        public Name(string fname);

 

        public string FName { get; set; }

    }

}

Right now, I think my focus will be on writing F# code that plays well/looks natural to C# developers. I’ll keep that point of view until I see a reason to change.

Leave a comment

What am I doing now?

A long while back, I mentioned that my wife, Jean, and I were looking at starting up a company. Well, we’ve done a lot of thinking about what the product should do and how this should be done. Because of other recent activities, I haven’t had a lot of time to execute on the idea. The fact of the matter is that we still like the underlying concept, but the implementation concept has morphed several times since we had the idea. The biggest changes are these:

  1. F#: A VS2010 language (currently in Beta)
  2. Azure: A Cloud platform

F# is a functional .NET language. I’ve always been a fan of functional programming as it typically allows me to write my applications using fewer lines than what I would do in pure imperative mode. For better or worse, imperative languages are still center stage (and have been for decades). In order to pay the bills, it is easier to find work using C++/C#/Java than using LISP/Prolog/Scala. However, with F# (an OCaml based language), we have a chance of seeing functional programming go mainstream. I have a project in mind that needs a .NET language, so why not use the project as a means to really get into F#.

The second thing that happened is the beta release of Azure at the 2008 PDC. A big concern of mine has been hosting the set of servers that will eventually be needed if the web site idea takes off. Yes, I’m familiar with how to make sites scalable, how to buy a server, etc. I’m also familiar with the fact that more servers means more people I’d have to hire who may or may not have the chops to manage a large-ish web site. The cloud stuff is very appealing to me as it allows someone who worries only about managing servers do whatever that is. I can then focus on conserving space, writing better algorithms, and paying a smaller price to keep that service up and running (yeah, I’m assuming that, like other managed services, the cost of going to the cloud is less that the cost of personnel + equipment + power + licensing).

So, until I either lose interest or get so swamped with work/life/whatever, expect to see the blog focus on F# and Azure stuff. Right now, I’m a noob.

Leave a comment