Again, I'm teaching myself this aspect of F# by referencing the Microsoft documentation on the topic.
So a quick rundown on the module concept as a recap:
- Modules remove members from the global namespace.
- Provide top-level modules and local modules.
- They can be nested.
- Are implemented as a class with static methods.
- Can contain members directly.
In contrast, a namespace:
- The first declaration in the file must be the namespace.
- Cannot contain members directly.
- Can contain types and modules.
- Can be declared implicitly as part of a module declaration.
- Can be nested (but slightly different syntax from modules).
- Namespaces can span multiple files.
So this makes a lot of sense if you think of it from the perspective of C#. A module is just a class with static members. A namespace is a namespace, just like you would expect in C#.
Example time. Explicit namespace declaration:
namespace Meow
module One =
let time = 40
Implicit namespace declaration:
module Meow.One
let time = 40
You can also nest namespaces:
namespace Meow
// Some code
namespace Meow.Blah
// More code
Well, that seems pretty straightforward now that I understand what's going on. Next question:
- Ok, now I've got modules and namespaces, but how do I include them in another file?
The answer is:
// Let's import a core framework component:
open System.IO
There are a few potential side effects for how F# handles ambiguities between the namespaces. The documentation says:
The F# compiler does not emit an error or warning when ambiguities occur when the same name occurs in more than one open module or namespace.I tried this and I got the following errors:
> open List;;
open List
-----^^^^
/Users/Matthew/Desktop/stdin(51,6): error FS0892: This declaration opens the module 'Microsoft.FSharp.Collections.List', which is marked as 'RequireQualifiedAccess'. Adjust your code to use qualified references to the elements of the module instead, e.g. 'List.map' instead of 'map'. This change will ensure that your code is robust as new constructs are added to libraries.
This makes me think that there was probably a change in this rule since the documentation was last updated.
So I'm pretty sure that this answers all of my immediate questions about modules and namespaces in F#. I'm sure I'll have more as I continue learning, but for now I feel like I've got the concepts.
See Also:
F# Modules
No comments:
Post a Comment