是否可以在本地限制模块的导入,最好将其与 Module Abbreviations
结合使用?目标是避免使用来自导入的符号污染我当前的模块。
例如(受 OCaml 启发)类似的东西:
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)
另外有没有办法用命名空间实现类似的东西?
最佳答案
The goal is to avoid polluting my current module with symbols from imports.
请注意
open Array
在 F# 中是不允许的(与 OCaml 相反)。您可以在模块上使用缩写,但只能在全局范围内:
module A = Microsoft.FSharp.Collections.Array
您可以使用 Array 代替 Microsoft.FSharp.Collections.Array。所以你的代码是:
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
如果您想对数组和列表重复使用相同的代码,您可能需要使用
Seq
模块:let elementsGreaterThan n =
[1..100] |> Seq.filter (fun x -> x > n)
关于f# - 如何将 F# 中的模块导入限制在本地范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5633672/