Namespaces in F#
April 2, 2017 Leave a comment
The main purpose of namespaces in F# is to group related types in one container and avoid name clashes of types. Namespaces are declared using the “namespace” keyword like in many other popular languages. A significant difference between C#/Java and F# is that F# namespaces can only contain type declarations. They cannot hold any values, i.e. anything that’s declared using the “let” keyword. They are only containers for types, i.e. elements that are declared using the “type” keyword.
A single F# source file (.fs) can contain multiple namespaces. A namespace starts with the namespace declaration and ends either at the end of the source file or at the next namespace declaration. Here’s an example with two namespaces where each namespace has a single type:
namespace com.mycompany.domains.book type Book = { title: string; numberOfPages:int; author: string } with member this.takesLongTimeToRead = this.numberOfPages > 500 namespace com.mycompany.domains.address type Address = { street: string; city: string; number: int; }
If we try to add a value in a namespace then we’ll get a compiler error:
namespace com.mycompany.domains.address let f = printf "Hello"
Namespaces cannot contain values. Consider using a module to hold your value declarations.
It’s of course possible to use types from different namespaces. The F# equivalent of a using/import statement is “open”:
namespace com.mycompany.domains.order open com.mycompany.domains.address type Order (product:string, value: int, address:Address) = member this.Product = product member this.Value = value member this.Address = address
Here’s an example of building a Book type and printing its title and whether it takes a long time to read from the Main entry point:
namespace com.mycompany.entry open System open com.mycompany.domains.book module Main = [<EntryPoint>] let main args = let myBook = {title = "F# for beginners"; numberOfPages = 600; author = "John Smith"} let longTimeOrNot = myBook.takesLongTimeToRead printfn "Book title: %s, takes long to read: %b" myBook.title longTimeOrNot let keepConsoleWindowOpen = Console.ReadKey() 0
The ‘keepConsoleWindowOpen” value is only there to keep the console window open so that we can see the output. Here’s the output:
Book title: F# for beginners, takes long to read: true
View all F# related articles here.