I have a problem in understanding the exact difference between modules and namespaces in F# and when using one or the other. Well, they both are considered in order to incapsulate code and define a hierarchy to get our projects well organized.
Modules have many features: they can contain values, types of all kinds and these elements can be defined public
, protected
or internal
too.
But, when using modules?
I understood also that modules are finally mapped as classes in MSIL (Intermediate Language). So a module is a class, is a type.... My doubts' magnitude improve....
When using modules??? Are they useful?
D. Syme also argues that modules are extensible, so I assume they are like namespaces from this point of view.
I cannot understand the reason to use them.
Thankyou
A module is a way which is used to organize the code in separate files and can execute in their local scope, not in the global scope. A namespace is a way which is used for logical grouping of functionalities with local scoping.
In Python-speak, modules are a namespace—a place where names are created. And names that live in a module are called its attributes. Technically, modules correspond to files, and Python creates a module object to contain all the names defined in the file; but in simple terms, modules are just namespaces.
In the context of F#, a module is a grouping of F# code, such as values, types, and function values, in an F# program. Grouping code in modules helps keep related code together and helps avoid name conflicts in your program.
Namespaces are simply named JavaScript objects in the global namespace. This makes namespaces a very simple construct to use. Unlike modules, they can span multiple files, and can be concatenated using outFile .
One major difference:
.NET namespaces cannot hold values (let definitions) while modules can.
In the IL/Bytecode level, a module is compiled to a .NET class, not a .NET namespace.
When to use modules?
For a small and specific task, F# and other FPs usually follow the pattern of bottom up programming: you decompose your task into a set of small functions and then you group these functions into a module.
The answer is that it is just so natural to use a module to group a set of related functions and other F# values and types together.
While a namespace is used to group bigger things: e.g. all classes for Matrix operations.
Module is not a static class (in C# sense) Modules can hold special F# values, e.g. curried functions; while a static class cannot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With