Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# coding style - static vs instance methods

I've noticed that static methods seem more popular in F# than C#. In C#, you'd always add an element to a collection by calling an instance method:

mySet.Add(elem);

But in F# there is usually an equivalent static method:

mySet.Add(elem)
// OR
Set.Add elem mySet

And I've seen the latter form quite often in samples. Both appear to me completely identical both semantically and functionally, but coming from a C# background, using the instance method feels more natural. Which is better style in F# and why?

like image 547
Asik Avatar asked Aug 01 '12 19:08

Asik


1 Answers

In addition to the reasons mentioned in that answer related to type inference, in functional style is more natural to send a function as a parameter. If it is an instance method you will have to write something like this:

myHigherOrderFunction (fun (x:MyType) -> x.myFunctionAsMethod)

But if it is defined as a static method you can write:

myHigherOrderFunction MyType.myFunctionAsMethod

which is more elegant, easier to write (to read as well) and is almost the same syntax as when sending a regular let bound function.

An instance method requires an instance of the type in order to access the function (the method), in OOP this is not an issue because you think in sending messages to objects but in FP, functions alone (without instances) are first class citizens.

To access a static method you need to specify the Class, you can see the Class as a kind of container (like modules or namespaces) with functions.

like image 93
Gus Avatar answered Sep 20 '22 00:09

Gus