BT

Borrowing Functional APIs from F#

| by Jonathan Allen Follow 576 Followers on Nov 21, 2007. Estimated reading time: 1 minute |

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 Stage
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.

Tell us what you think

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

Email me replies to any of my messages in this thread

No F# code in this post by Neil Bartlett

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

Email me replies to any of my messages in this thread

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

Email me replies to any of my messages in this thread

1 Discuss

Login to InfoQ to interact with what matters most to you.


Recover your password...

Follow

Follow your favorite topics and editors

Quick overview of most important highlights in the industry and on the site.

Like

More signal, less noise

Build your own feed by choosing topics you want to read about and editors you want to hear from.

Notifications

Stay up-to-date

Set up your notifications and don't miss out on content that matters to you

BT