Search code examples
f#structure

F# Library structure


I'm doing some restructuring of a project of mine, and decided to make a separate library project for a big part of it.

My problem lays in that I have multiple files with modules where many of them should be hidden from user API, how do I achieve this? I have not tried this before so are unfamiliar to how the library structure are different from commandline projects, and how to scope things correctly. If I can see every file in the lib project from other project why do we have the Library.fs file?

To formalize a little. Say that I have SomeCode.fs and Library.fs

SomeCode.fs

module SomeCode

type SomeType = ...

let someFunc1 ... = ...

// things to hide here

// depend on hidden code
let SomeFunc2 ... = ... 

Library.fs

namespace SomeLib

module Mod1 = ...

This is intended to target other F# project. How to structure this so the API would only see the right things, and still be maintainable?


Solution

  • internal is your friend here. If you declare a module

    module internal MyNamSpace.MySecretModule
    

    this is only accessible from within your project.

    The module Library you keep public, and this is your API.

    internal can also be used on individual functions, in case you want to hide just some functions.

    A fairly common way of hiding part of a module is also to employ the following pattern

    module MyModule =
    
        [<AutoOpen>]
        module internal MySecretModule =
            let apa = 1
            // Bunch of other internal stuff
    
        // Can use stuff from MySecretModule, but other projects cannot
        let bepa = apa + 1