BT

InfoQ Homepage News Borrowing Functional APIs from F#

Borrowing Functional APIs from F#

Bookmarks

The Common Language Specification ensures that any conforming .NET language can access libraries created by any other language. This means imperative languages like VB and C# can call functional libraries created primarily for F#. In fact, many can be converted directly into C# code.

Dustin Campbell illustrates this by showing how even simple C# expressions can be reduced in length. He starts with this code,

int[] a = new int[20];
for (int x = 0; x < a.Length; x++)
a[x] = x + 1;

Instead of a specific code recipe, this F# code says (in a more declarative fashion), "create an array of 20 elements, and use this function to initialize each element." An interesting feature of the F# version is that the type of the array is never declared. Because the compiler can infer that the result of the passed function (fun x -> x + 1) will be an int, "a" must be an int array.

To me, this code is beautiful. In addition, it is declarative instead of imperative; it describes what should be done but doesn't dictate exactly how it should be done. When I see such elegant code, I immediately start trying to figure out which of its aspects could be used to improve the code in my daily C# work.

Dustin goes on to show a C# function that allows for this syntax.

var a = ArrayEx.Create(20, x => x + 1);

It should be noted that these techniques work equally well in VB.

Rate this Article

Adoption
Style

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Community comments

  • No F# code in this post

    by Neil Bartlett /

    Your message is awaiting moderation. Thank you for participating in the discussion.

    You've quoted the C# code where I think you intended to quote the F# code.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

BT

Is your profile up-to-date? Please take a moment to review and update.

Note: If updating/changing your email, a validation request will be sent

Company name:
Company role:
Company size:
Country/Zone:
State/Province/Region:
You will be sent an email to validate the new email address. This pop-up will close itself in a few moments.