Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is it possible 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?

like image 783
Alexander Battisti Avatar asked Apr 12 '11 10:04

Alexander Battisti


1 Answers

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)
like image 183
Laurent Avatar answered Nov 15 '22 10:11

Laurent