Core.Option module extension in F #

I want to expand one of the existing "core" modules, for example Core.Option:

module Microsoft.FSharp.Core.Option

    let filter predicate op =
        match op with
        | Some(v) -> if predicate(v) then Some(v) else None
        | None -> None

(I know about the function bind, but I think that the method filterfor parameters is more convenient in some cases).

But unfortunately, I cannot use the method filterwithout an explicitly open namespace Microsoft.FSharp.Core:

// Commenting following line will break the code!
open Microsoft.FSharp.Core

let v1 = Some 42
let v2 = v1 |> Option.filter (fun v -> v > 40)

printfn "v2 is: %A" v2

In most cases, we cannot use functions from the module without opening the corresponding namespace. The F # compiler "automatically opens" some predefined (main) namespace (for example Microsoft.FSharp.Core), this will not lead to scope methods from the "extension modules", and we still have to open the namespace manually.

My question is: are there any workarounds?

"" - ?

// Lets custom Option module in our custom namespace
module CustomNamespace.Option

    let filter predicate op = ...

// On the client side lets open our custom namespace.
// After that we can use both Option modules simultaneously!
open CustomNamespace

let v1 = Some 42
let b = 
    v1 |> Option.filter (fun v -> v > 40) // using CustomNamespace.Option
    |> Option.isSome // using Microsoft.FSharp.Core.Option
+5
3

AutoOpen ?

[<AutoOpen>]
module Microsoft.FSharp.Core.Option

    let filter predicate op =
        match op with
        | Some(v) -> if predicate(v) then Some(v) else None
        | None -> None

, . :

namespace Microsoft.FSharp.Core
module Option =
    let filter predicate op =
        match op with
        | Some(v) -> if predicate(v) then Some(v) else None
        | None -> None

[<assembly:AutoOpen("Microsoft.FSharp.Core")>]
do ()

:

[<EntryPoint>]
let main args = 
    let f () = Some "" |> Option.filter (fun f -> true)
    Console.WriteLine("Hello world!")
    0
+5

, Taha: /alias. . , F #, , .

, , :

namespace Microsoft.FSharp.Core

module Option =

    let filter predicate op =
        match op with
        | Some(v) -> if predicate(v) then Some(v) else None
        | None -> None

namespace USERCODE

module Option = Microsoft.FSharp.Core.Option

module M =

    let test () =
        Some 1
        |> Option.filter (fun x -> x > 0)
        |> Option.map (fun x -> x + 1)

- , , . Microsoft.FSharp.Core, , .

+5

To extend the F # module, create another with the same name:

module Option =

    let filter predicate op =
        match op with
        | Some v  -> match predicate v with true -> Some v | false -> None
        | None    -> None


let v1 = Some 42
let v2 = v1 |> Option.filter (fun v -> v > 40)

printfn "v2 is: %A" v2
+3
source

All Articles