MiloDC
MiloDC

Reputation: 2415

F# and tuple output

Over at http://diditwith.net, I see that, in F#, it isn't strictly necessary to pass out parameters to a function that otherwise requires them. The language will auto-magically stuff the result and the output parameter into a tuple. (!)

Is this some kind of side effect (pardon the pun) of the general mechanics of the language, or a feature that was specifically articulated in the F# specification and deliberately programmed into the language?

It's an awesome feature, and if it was expressly put into F#, then I'm wondering what other nuggets of gold like this are lurking within the language, because I've pored over dozens of web pages and read through three books (by D. Syme, T. Petricek, and C. Smith) and I hadn't seen this particular trick mentioned at all.

EDIT: As Mr. Petricek has responded, below, he does mention the feature in at least two places in his book, Real-World Functional Programming. My bad.

Upvotes: 5

Views: 365

Answers (2)

Tomas Petricek
Tomas Petricek

Reputation: 243061

This is not a side-effect of some other, more general, mechanism in the F# language.

It has been added specifically for this purpose. .NET libraries often return multiple values by adding out (or ref) parameters at the end of the method signature. In F#, returning multiple values is done by returning tuple, so it makes sense to turn the .NET style into the typical F# pattern.

I don't think F# does many similar tricks, especially when it comes to interoperability, but you can browse through some of the handy snippets here and here.

(I quickly checked and Real-World Functional Programming mentions the trick briefly on pages 88 and 111.)

Upvotes: 6

kvb
kvb

Reputation: 55185

This is a specific feature to make interop with .NET methods more pleasant - all trailing out parameters can instead be treated as part of the return value (but note that this only affects trailing out parameters, so a method with the C# signature like void f(out int i, int j) can't be called this way).

Arguably, out parameters are just a way to work around the lack of tuples in .NET 1.0, anyway. It seems likely that many methods that use them would be written differently if they targeted later versions of the framework (by using Nullable<_> types or tuples as return types).

Upvotes: 4

Related Questions