Monday, October 19, 2009

Be a Better Polyglot with F#'s CompiledNameAttribute

F# introduces the CompiledNameAttribute with the October 2009 CTP. This attribute provides a way to specify the compiled name of a method or type written in F#. The big advantage here is the ability to prevent having to compromise on your naming schemes in either F# or any other language. Internally to the assembly, you can still use the names you give to the constructs when you define the construct. Externally, however, the name will be compiled into a ".NET Friendly" name, which you can specify using the CompiledNameAttribute.

Take, for example, the extension method I wrote in my previous post. Using the CompiledNameAttribute, I can refer to this in F# using one name, and in C# using another name.

[<System.Runtime.CompilerServices.ExtensionAttribute>]
module public Morton.Extensions.EnumerableExtensions
[<Microsoft.FSharp.Core.CompiledNameAttribute("OutputAll")>]
[<System.Runtime.CompilerServices.ExtensionAttribute>]
let internalNameGoesHereForOutputting (_this:System.Collections.Generic.IEnumerable<'T>) =
for x in _this do System.Console.WriteLine x |> ignore


Note the internal name here is "internalNameGoesHereForOutputting" while the external name will be "OutputAll".

This is a very nice feature indeed, and I'd love to see it implemented in other languages as well. Kudos to Don Syme and the rest of the F# team for this one. This is an excellent step towards polyglot programming: translation.