开发者

How to restrict the import of a Module in F# to a local scope?

开发者 https://www.devze.com 2023-02-24 05:28 出处:网络
Is it 开发者_如何学JAVApossible to locally restrict the import of a module, preferrably combining this with Module Abbreviations? The goal is to avoid polluting my current module with symbols from imp

Is it 开发者_如何学JAVApossible to locally restrict the import of a module, preferrably combining this with Module Abbreviations? The goal is to avoid polluting my current module with symbols from imports.

e.g. (inspired by OCaml) something like that:

let numOfEvenIntegersSquaredGreaterThan n =
    let module A = Microsoft.FSharp.Collections.Array in
        [|1..100|] |> A.filter (fun x -> x % 2 = 0)
                   |> A.map    (fun x -> x * x)
                   |> A.filter (fun x -> x > n)
                   |> A.length

let elementsGreaterThan n =
    let module A = Microsoft.FSharp.Collections.List in
        [1..100] |> A.filter (fun x -> x > n)

Additionally is there a way to achieve something similar with namespaces?


The goal is to avoid polluting my current module with symbols from imports.

Note that open Array is not allowed in F# (contrary to OCaml). You can use abbreviations on modules, but only in the global scope:

module A = Microsoft.FSharp.Collections.Array

Instead of Microsoft.FSharp.Collections.Array, you can use Array. So your code would be:

let numOfEvenIntegersSquaredGreaterThan n =
    [|1..100|] |> Array.filter (fun x -> x % 2 = 0)
               |> Array.map    (fun x -> x * x)
               |> Array.filter (fun x -> x > n)
               |> Array.length

If you want to reuse the same code for Arrays and Lists, you might want to use the Seq module:

let elementsGreaterThan n =
    [1..100] |> Seq.filter (fun x -> x > n)
0

精彩评论

暂无评论...
验证码 换一张
取 消