Sharing types across F# .fsx files

前端 未结 3 1290
感情败类
感情败类 2021-01-11 11:53

Is there a way to share types across fsx files?

When using #load to load the same file containing a type from multiple FSX files they seem to be prefixed into a diff

3条回答
  •  北海茫月
    2021-01-11 12:00

    As for

    http://msdn.microsoft.com/en-us/library/dd233169.aspx

    [.fsx files are] used to include informal testing code in F# without adding the test code to your application, and without creating a separate project for it. By default, script files are not included in the build of a project even when they are part of a project.

    This means that if you have a project with enough structure to be having such dependency problems, you should not use .fsx files, instead write modules/namespaces using .fs files. That is, you really should compile them types into an assembly.

    The f# interactive interpreter generates assembly for each loaded files. If you load a file twice, the bytecode is generated twice, and the types are different even if they have the same definition and the same name. This means that there is no way for you to share types between two .fsx files, unless one of them includes the other.

    When you #load a file which has the same types as ones already present in your environment, the f# interactive interpreter can use two different strategy:

    1. refuse to load the file if conflicts with existing names arises (complaining that some stuff is already defined)
    2. put the names in FS_00xx namespace (so that they are actually different types from the ones you already loaded), eventually opening the resulting namespace so that names are available from interactive session.

    Since fsx files are supposed to be used as informal test it is more user-friendly to use the second approach (there are also technical reason for which the second approach is used, mainly dependent on .net VM type system, and the fact that existing types cannot be changed at runtime).

提交回复
热议问题