代码之家  ›  专栏  ›  技术社区  ›  Massif

在签名文件中共享区分的联合

  •  2
  • Massif  · 技术社区  · 15 年前

    我有一个被区别的联合,我想用它作为我在签名文件中公开的函数的参数。目前我对代码的定义如下:

    Signature.fsi:

    type Union =
    | Part of string
    | Part2 of int
    
    val Func: Union -> unit
    

    在单独的fs文件中定义func。

    问题是,当我这样做时,fs文件无法获取联合定义,因此创建part或part2值的代码失败。除非我在使用联合的fs文件中再次定义联合。

    例如:

    Signature.fs:

    type Union =
    | Part of string
    | Part2 of int
    
    let Func input:Union =
        ignore
    

    其他文件

    type Union =
    | Part of string
    | Part2 of int
    
    let DoSomething =
        Func(Part("Test"))
    

    每次失败都不重新定义联合。我错过了一些明显的东西吗?说到f,我还是很环保的。

    2 回复  |  直到 15 年前
        1
  •  4
  •   Juliet    15 年前

    我想你在找这样的东西:

    Test.fsi:

    #light
    
    type Union =
        | Part of string
        | Part2 of int
    
    val awesome: Union -> unit
    

    Test.fs:

    #light
    
    type Union =
        | Part of string
        | Part2 of int
    
    let awesome (x :Union) = printfn "%A" x
    

    这将创建一个名为 Test 您可以从其他文件访问:

    AnotherTest.fs:

    #light
    
    let wickedAwesome() =
        Test.awesome(Test.Part("hellz yeah!"))
    

    如果你 open 这个 试验 模块,您可以按如下方式重新编写anothertest.fs:

    #light
    open Test
    
    let wickedAwesome() =
        awesome (Part("hellz yeah!"))
    

    F# Modules and Namespaces 更全面的教程。

        2
  •  1
  •   ShuggyCoUk    15 年前

    您的F项目需要按正确的顺序排列文件。这意味着将包含func定义的文件放在比使用它的文件更高的位置(字面上)。您可能会考虑将这种防御放在FSI文件中。

    我会指出,使用类型名func是一个非常糟糕的想法,因为func的普遍性(以及大多数用户的假设)意味着 3.5 standard (* -> x) delegates .