6

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?

Alexander Battisti
  • 2,178
  • 2
  • 19
  • 24

1 Answers1

1

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)
Laurent
  • 2,951
  • 16
  • 19
  • Thanks for your answer Laurent. Using Array was just an arbitrary - and in retrospect unlucky - example though. My goal is to open an arbitrary Module (or namespace) _only_ within a limited scope like within a single 'let binding'. If I understand you correctly this is (currently?) not possible in F#? – Alexander Battisti Apr 12 '11 at 12:19
  • Indeed. I hope it will be possible in the future. In the meantime, I think adding a few abbreviations in the global scope doesn't pollute much (but try to avoid 1-char names). – Laurent Apr 12 '11 at 12:23