tags:

views:

721

answers:

4

Is it possible to split an F# module across files?

According to the book I have it is, but the book is probably outdated (Foundations of F#)

+2  A: 

Apparently not:

C:\temp\Tim>type 1.fs 2.fs

1.fs


#light
module Module

let sayHello1 = printfn "Hello, "

2.fs


#light
module Module

let sayHello2 = printfn "world!"

C:\temp\Tim>fsc 1.fs 2.fs
Microsoft F# Compiler, (c) Microsoft Corporation, All Rights Reserved
F# Version 1.9.6.2, compiling for .NET Framework Version v2.0.50727

2.fs(2,1): error FS0191: An implementation of the file or module Module has already been given.
Tim Robinson
That's to bad, because I'm doing data parsing and there are many different data structures so I'm generating a very very very long F# file...
TimothyP
Time to break it up into regular .NET classes instead of modules? Or more than one F# module?
Tim Robinson
Unfortunately F# doesn't support partial classes, so you can't even split a regular .NET class over several source files.
Tim Robinson
+1  A: 

I sometimes split a type over several places, like this:

module Foo

type Partial = Bar | BarInt of int

module Bar

type Foo.Partial with
    member x.Extend = 5


let b = Foo.Bar.Extend

where modules Foo and Bar are in different files.

Kurt Schelfthout
+2  A: 

Like Kurt says, you can add extension methods to types, and thus

// File1.fs
namespace Foo

type Mine() =
    static member f1 () = ()

then

// File2.fs
type Foo.Mine with
    static member f2() = ()

Foo.Mine.    // both f1 and f2 here

Since it's a class and not a module, you lose the ability to do 'open Mine' (but gain the ability to overload); thus this may or may not be an acceptable alternative for you depending on exactly what you're doing.

Brian
+3  A: 

The type extensions are cool, and hopefully they will allow to be cross file, while still being intrinsic. If you do a type extension in the same file, it compiles to one class, and the extension has access to private members and so on. If you do it in another file, it's just an "optional" extension, like C# static extension methods. (Even though the F# specs say differently.)

I'd be surprised if this isn't addressed at some point, if only for designer support. If intrinsic type extensions could be anywhere in the assembly, that'd be pretty slick.

Another option, which might not be what you want, is to create a type and a module, call the module the same name, and then add the ModuleSuffix flag to it:

type Foo() = 
    static member Bar = 1

[<CompilationRepresentationAttribute(CompilationRepresentationFlags.ModuleSuffix)>]
module Foo =
    let Baz = 2

printfn "%d %d" Foo.Bar Foo.Baz

This is used in the F# libraries, so they can have a type List or whatever, along with tons of helper stuff in a module.

MichaelGG