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.

%d bloggers like this: