What the difference between a namespace and a module in F#?
Asked Answered
S

1

99

I've just started learning F# (with little prior experience with .NET) so forgive me for what is probably a very simple question: What the difference between a namespace and a module in F#?

Thanks

Dave

Edit: Thanks for the answer Brian. That's what I wanted to know. Just a clarification: can you also open a namespace as well (similar to C# using statement)?

Sermon answered 27/4, 2009 at 20:33 Comment(1)
And one more note, when you open a namespace in F#, like System, you get access to its sub namespaces as well. So in C#, if you open System, you still need to write "System.IO.File". In F#, you can write "IO.File". I find this makes code far nicer.Berryman
M
104

A namespace is a .Net thing, common in many industrial-strength languages, just a way to organize frameworks and avoid naming conflicts among different libraries. Both you and I can define a type "Foo" and use them both in a project, provided they are in different namespaces (e.g. NS1.Foo and NS2.Foo). Namespaces in .Net contain types.

A module is an F# thing, it is roughly analogous to a "static class"... it is an entity that can hold let-bound values and functions, as well as types (note that namespaces cannot directly contain values/functions, namespaces can only contain types, which themselves can contain values and functions). Things inside a module can be referenced via "ModuleName.Thing", which is the same syntax as for namespaces, but modules in F# can also be 'opened' to allow for unqualified access, e.g.

open ModuleName
...
Thing  // rather than ModuleName.Thing

(EDIT: Namespaces can also similarly be opened, but the fact that modules can contain values and functions makes opening a module more 'interesting', in that you can wind up with values and functions, e.g. "cos", being names you can use directly, whereas in other .Net languages you'd typically always have to qualify it, e.g. "Math.cos").

If you type in code at 'the top level' in F#, this code implicitly goes in a module.

Mezuzah answered 27/4, 2009 at 21:1 Comment(4)
That cannot be fully correct. modules exist in C# as well, do they not?: https://mcmap.net/q/218559/-what-is-a-module-in-netMantling
Well, there's a netmodule, which is a .NET thing, and there's an F# module, which is an F# thing, and I think VB maybe has a module construct, and classes are 'modules' in the general software engineering sense... But the original question was about F# modules.Mezuzah
There's a great link here, which explains the relationship between an assembly and a net module - a single assembly could contain 2 netmodules written in 2 different languages.Shumpert
Resembles 'using static' in C# 6Saudra

© 2022 - 2024 — McMap. All rights reserved.