开发者

DIfference between Modules and Namespaces in F#

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 mod开发者_开发百科ules 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


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.


As Yin Zhu says, modules can hold values. And you can open modules like namespaces. These two features together are why in F# you can do things like

let z = max x y

whereas in a language like C# you'd always have to say something like

var z = Math.Max(x,y)
//      ^^^^^   can't call methods from elsewhere without a qualifier

and use a qualified name (SomeClass.Method) rather than just a name (letBoundFunction). So you can use modules when you want people to be able to open you module Foo and call bar by just saying bar rather than Foo.bar everywhere. (This is especially useful for operators, e.g. if you define a bunch of user-defined operators (such as +++ or whatnot) in a library, by putting them in a module, people can open the module and then just use e.g. x +++ y rather than cumbersome stuff like (Foo.+++) x y or whatever.)

Note that while F# puts code in a .fs file in a module (with the name of the file) by default, you can change this by having the first code in the file be a namespace declaration, e.g.

namespace Yadda
// declare some types or whatnot, they go in namespace Yadda

or by declaring your own module

module Blah
// stuff goes in Blah module

at the top of the file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜