Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does F# have free functions?

Tags:

function

c#

math

f#

Does every function has to be inside a type like in C#? Or does F# has free functions?

Also what about functions I have seen all over some F# code like, cos, sin, etc. Are they calls to Math.Cos, Math.Sin?

Also why did they provide cos, sin, etc like that instead of Math.Cos, Math.Sin?

like image 581
Joan Venge Avatar asked Nov 29 '22 19:11

Joan Venge


2 Answers

F# can have functions scoped in modules (instead of classes).

The CLR implements these, internally, as:

as a common language runtime (CLR) class that has only static members

They look like "free functions" within the scope of a module.

like image 183
Reed Copsey Avatar answered Dec 04 '22 12:12

Reed Copsey


As Reed mentioned, functions can be defined within modules a la other ML languages, but they can also be defined on types like other .NET languages (and in fact modules are also compiled to classes). Within F#, modules can be opened to access the functions without having to use the module name each time, and modules are automatically created on a per-file basis if they aren't explicitly declared.

As to why there are separate cos, etc. functions instead of merely relying on .NET's built-in Math.Cos, etc., there are probably several reasons:

  1. Uniformity: cos looks much more idiomatic in F# than calling the static method System.Math.Cos.
  2. Static constraints: cos doesn't just work on floats in F#, it also works on float32s and on any type which exposes a static Cos method, so you can create your own types to which the cos function can be applied.

I'd guess that truly free functions aren't allowed because there are many .NET languages which don't expose convenient access to them, so using them would present a barrier to cross-language interoperability. The CLR itself does support free functions, and some languages such as C++/CLI do use them, but most languages compile functions into classes (even if that's not how it looks from a source code perspective, as in F#).

like image 24
kvb Avatar answered Dec 04 '22 11:12

kvb