Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private modifier for F# types

Tags:

f#

If we have

module M

type private A = B | C

(...)

The private modifier means that A will only be usable from within the module M. But in this case:

namespace N

type private A = B | C

(...)

What will be the effect of that private modifier? It doesn't make sense for a CLR namespace to have private members, as the namespace can be extended at will, so will that private modifier have any effect at all?

like image 613
Gustavo Guerra Avatar asked Mar 04 '13 14:03

Gustavo Guerra


1 Answers

If you use the private modifier like that within a namespace, it makes the type or module private to the file -- that is, the type can be used by anything below it within the same file.

When the type is compiled, the F# compiler will treat it as internal within the .NET metadata. (Which makes sense, since the type is really internal -- the compiler just enforces the constraint that it can only be used by types/functions within the same file.)

I use this feature quite often BTW -- it's nice for small helper types that are only used internally in a few spots since it keeps them from cluttering up the IntelliSense.

EDIT: Another cool trick you can use this for is to create file-scoped, "built-in" helper functions.

If you create a module like this, the functions in it will be automatically available to anything below it (thanks to [<AutoOpen>]) but since the module is marked private the functions won't clog up your IntelliSense (when working on your other source files) or hide existing functions.

[<AutoOpen>]
module private Helpers =
    let [<Literal>] blah = "blah"

    let lessThanTwo value =
        value < 2.0
like image 61
Jack P. Avatar answered Sep 30 '22 14:09

Jack P.