Prevent shadowing of Ok and Error with FParsec? - f#

Suppose I have a test like this:
module MyTests
open Xunit
open FParsec
open FsUnit.Xunit
open MyParsers
[<Fact>]
let ``pfoo works as expected`` () =
let text = "blahblahblah"
let actual =
match run pfoo text with
| Success (x, _, _) -> Result.Ok x
| Failure (s, _, _) -> Result.Error s
let expected : Result<Foo, string> =
Result.Ok
{
Foo = "blahblahblah"
}
expected
|> should equal actual
open FParsec will shadow Ok so that I need to fully qualify it like Result.Ok.
This is pretty annoying. Is there a good way to "open" Result again so that I can write Ok unqualified?

It's not Result that you need to "open", but Microsoft.FSharp.Core, which is the module in which Result and both its constructors are defined. This module is open by default, but you can open it again to have its definitions closer in the scope:
open Xunit
open FParsec
open FsUnit.Xunit
open MyParsers
open Microsoft.FSharp.Core
Alternatively, you can alias just the Ok identifier:
let Ok = Result.Ok
let x = Ok "foo" // x : Result<string, _>
I prefer this latter method, because it minimizes the impact surface and thus reduces the chance of unexpected surprises.
The downside is that the aliased Ok won't work for pattern matching:
match x with
| Ok y -> ... // This is Ok from FParsec
If you need pattern matching as well, you'll have to alias the matcher too:
let (|Ok|Error|) x = match x with | Result.Ok o -> Ok o | Result.Error e -> Error e
At which point I would probably fall back to reopening the module.

Related

final output of Result, in F#

This seems like a question that has an ultra simple answer, but I can't think of it:
Is there a built in method, within Result, for:
let (a: Result<'a, 'a>) = ...
match a with
| Ok x -> x
| Error e -> e
No, because this function requires the Ok type and the Error type to be the same, which makes Result less general.
No, there isn't any function which will allow you to do so. But you can easily define it:
[<RequireQualifiedAccess>]
module Result =
let join (value: Result<'a, 'a>) =
match value with
| Ok v -> v
| Error e -> e
let getResult s =
if System.String.IsNullOrEmpty s then
Error s
else
Ok s
let a =
getResult "asd"
|> Result.join
|> printfn "%s"
It doesn't make Result less general (as said by #brianberns), because it's not an instance member. Existence of Unwrap doesn't make Task less general
Update
After more scrupulous searching inside FSharpPlus and FSharpx.Extras I've found necessary function. It's signature ('a -> 'c) -> ('b -> 'c) -> Result<'a,'b> -> c instead of Result<'a, 'a> -> 'a and it's called Result.either in both libraries (source 1 and source 2). So in order to get value we may pass id as both parameters:
#r "nuget:FSharpPlus"
open FSharpPlus
// OR
#r "nuget:FSharpx.Extras"
open FSharpx
getResult "asd"
|> Result.either id id
|> printfn "%s"
Also it's may be useful to define shortcut and call it Result.join or Result.fromEither as it's called in Haskell

How to use HtmlDocument's TryGetHtml

Say I have a a function
let GetDataFromWebsite (url:string) =
let webpage = HtmlDocument.Load(url)
let html = webpage.TryGetHtml
html
(note that this will become a longer function once I work out how to use the TryGetHtml function)
This tells me that it has a return string -> unit -> HtmlNode option. What is this exactly returning and how do I use it? I have tried
match GetDataFromWebsite(#"...") with
| None -> "None"
| _ -> (fun a -> a.ToString())
|> printfn "%s"
but visual studio states that:
This expresion was expected to have type
'unit -> FSharp.Data.HtmlNode option'
but here has type
''a option'
Nearly there :)
TryGetHtml is a function, not a property, and you likely want to evaluate it instead of assigning it:
let GetDataFromWebsite (url:string) =
let webpage = HtmlDocument.Load(url)
let html = webpage.TryGetHtml() // note braces
html
Now it returns HtmlNode option you can pattern match on:
match GetDataFromWebsite(#"...") with
| None -> "None"
| Some x -> x.ToString()
|> printfn "%s"
This should compile without errors.

type mismatch error for async chained operations

Previously had a very compact and comprehensive answer for my question.
I had it working for my custom type but now due to some reason I had to change it to string type which is now causing type mismatch errors.
module AsyncResult =
let bind (binder : 'a -> Async<Result<'b, 'c>>) (asyncFun : Async<Result<'a, 'c>>) : Async<Result<'b, 'c>> =
async {
let! result = asyncFun
match result with
| Error e -> return Error e
| Ok x -> return! binder x
}
let compose (f : 'a -> Async<Result<'b, 'e>>) (g : 'b -> Async<Result<'c, 'e>>) = fun x -> bind g (f x)
let (>>=) a f = bind f a
let (>=>) f g = compose f g
Railway Oriented functions
let create (json: string) : Async<Result<string, Error>> =
let url = "http://api.example.com"
let request = WebRequest.CreateHttp(Uri url)
request.Method <- "GET"
async {
try
// http call
return Ok "result"
with :? WebException as e ->
return Error {Code = 500; Message = "Internal Server Error"}
}
test
type mismatch error for the AsyncResult.bind line
let chain = create
>> AsyncResult.bind (fun (result: string) -> (async {return Ok "more results"}))
match chain "initial data" |> Async.RunSynchronously with
| Ok data -> Assert.IsTrue(true)
| Error error -> Assert.IsTrue(false)
Error details:
EntityTests.fs(101, 25): [FS0001] Type mismatch. Expecting a '(string -> string -> Async<Result<string,Error>>) -> 'a' but given a 'Async<Result<'b,'c>> -> Async<Result<'d,'c>>' The type 'string -> string -> Async<Result<string,Error>>' does not match the type 'Async<Result<'a,'b>>'.
EntityTests.fs(101, 25): [FS0001] Type mismatch. Expecting a '(string -> string -> Async<Result<string,Error>>) -> 'a' but given a 'Async<Result<string,'b>> -> Async<Result<string,'b>>' The type 'string -> string -> Async<Result<string,Error>>' does not match the type 'Async<Result<string,'a>>'.
Edit
Curried or partial application
In context of above example, is it the problem with curried functions? for instance if create function has this signature.
let create (token: string) (json: string) : Async<Result<string, Error>> =
and then later build chain with curried function
let chain = create "token" >> AsyncResult.bind (fun (result: string) -> (async {return Ok "more results"}))
Edit 2
Is there a problem with following case?
signature
let create (token: Token) (entityName: string) (entityType: string) (publicationId: string) : Async<Result<string, Error>> =
test
let chain = create token >> AsyncResult.bind ( fun (result: string) -> async {return Ok "more results"} )
match chain "test" "article" "pubid" |> Async.RunSynchronously with
Update: At the front of the answer, even, since your edit 2 changes everything.
In your edit 2, you have finally revealed your actual code, and your problem is very simple: you're misunderstanding how the types work in a curried F# function.
When your create function looked like let create (json: string) = ..., it was a function of one parameter. It took a string, and returned a result type (in this case, Async<Result<string, Error>>). So the function signature was string -> Async<Result<string, Error>>.
But the create function you've just shown us is a different type entirely. It takes four parameters (one Token and three strings), not one. That means its signature is:
Token -> string -> string -> string -> Async<Result<string, Error>>
Remember how currying works: any function of multiple parameters can be thought of as a series of functions of one parameter, which return the "next" function in that chain. E.g., let add3 a b c = a + b + c is of type int -> int -> int -> int; this means that add3 1 returns a function that's equivalent to let add2 b c = 1 + b + c. And so on.
Now, keeping currying in mind, look at your function type. When you pass a single Token value to it as you do in your example (where it's called as create token, you get a function of type:
string -> string -> string -> Async<Result<string, Error>>
This is a function that takes a string, which returns another function that takes a string, which returns a third function which takes a string and returns an Async<Result<whatever>>. Now compare that to the type of the binder parameter in your bind function:
(binder : 'a -> Async<Result<'b, 'c>>)
Here, 'a is string, so is 'b, and 'c is Error. So when the generic bind function is applied to your specific case, it's looking for a function of type string -> Async<Result<'b, 'c>>. But you're giving it a function of type string -> string -> string -> Async<Result<string, Error>>. Those two function types are not the same!
That's the fundamental cause of your type error. You're trying to apply a function that returns a function that returns function that returns a result of type X to a design pattern (the bind design pattern) that expects a function that returns a result of type X. What you need is the design pattern called apply. I have to leave quite soon so I don't have time to write you an explanation of how to use apply, but fortunately Scott Wlaschin has already written a good one. It covers a lot, not just "apply", but you'll find the details about apply in there as well. And that's the cause of your problem: you used bind when you needed to use apply.
Original answer follows:
I don't yet know for a fact what's causing your problem, but I have a suspicion. But first, I want to comment that the parameter names for your AsyncResult.bind are wrong. Here's what you wrote:
let bind (binder : 'a -> Async<Result<'b, 'c>>)
(asyncFun : Async<Result<'a, 'c>>) : Async<Result<'b, 'c>> =
(I moved the second parameter in line with the first parameter so it wouldn't scroll on Stack Overflow's smallish column size, but that would compile correctly if the types were right: since the two parameters are lined up vertically, F# would know that they are both belonging to the same "parent", in this case a function.)
Look at your second parameter. You've named it asyncFun, but there's no arrow in its type description. That's not a function, it's a value. A function would look like something -> somethingElse. You should name it something like asyncValue, not asyncFun. By naming it asyncFun, you're setting yourself up for confusion later.
Now for the answer to the question you asked. I think your problem is this line, where you've fallen afoul of the F# "offside rule":
let chain = create
>> AsyncResult.bind (fun (result: string) -> (async {return Ok "more results"}))
Note the position of the >> operator, which is to the left of its first operand. Yes, the F# syntax appears to allow that in most situations, but I suspect that if you simply change that function definition to the following, your code will work:
let chain =
create
>> AsyncResult.bind (fun (result: string) -> (async {return Ok "more results"}))
Or, better yet because it's good style to make the |> (and >>) operators line up with their first operand:
let chain =
create
>> AsyncResult.bind (fun (result: string) -> (async {return Ok "more results"}))
If you look carefully at the rules that Scott Wlaschin lays out in https://fsharpforfunandprofit.com/posts/fsharp-syntax/, you'll note that his examples where he shows exceptions to the "offside rule", he writes them like this:
let f g h = g // defines a new line at col 15
>> h // ">>" allowed to be outside the line
Note how the >> character is still to the right of the = in the function definition. I don't know exactly what the F# spec says about the combination of function definitions and the offside rule (Scott Wlaschin is great, but he's not the spec so he could be wrong, and I don't have time to look up the spec right now), but I've seen it do funny things that I didn't quite expect when I wrote functions with part of the function definition on the same line as the function, and the rest on the next line.
E.g., I once wrote something like this, which didn't work:
let f a = if a = 0 then
printfn "Zero"
else
printfn "Non-zero"
But then I changed it to this, which did work:
let f a =
if a = 0 then
printfn "Zero"
else
printfn "Non-zero"
I notice that in Snapshot's answer, he made your chain function be defined on a single line, and that worked for him. So I suspect that that's your problem.
Rule of thumb: If your function has anything after the = on the same line, make the function all on one line. If your function is going to be two lines, put nothing after the =. E.g.:
let f a b = a + b // This is fine
let g c d =
c * d // This is also fine
let h x y = x
+ y // This is asking for trouble
I would suspect that the error stems from a minor change in indentation since adding a single space to an FSharp program changes its meaning, the FSharp compiler than quickly reports phantom errors because it interprets the input differently. I just pasted it in and added bogus classes and removed some spaces and now it is working just fine.
module AsyncResult =
[<StructuralEquality; StructuralComparison>]
type Result<'T,'TError> =
| Ok of ResultValue:'T
| Error of ErrorValue:'TError
let bind (binder : 'a -> Async<Result<'b, 'c>>) (asyncFun : Async<Result<'a, 'c>>) : Async<Result<'b, 'c>> =
async {
let! result = asyncFun
match result with
| Error e -> return Error e
| Ok x -> return! binder x
}
let compose (f : 'a -> Async<Result<'b, 'e>>) (g : 'b -> Async<Result<'c, 'e>>) = fun x -> bind g (f x)
let (>>=) a f = bind f a
let (>=>) f g = compose f g
open AsyncResult
open System.Net
type Assert =
static member IsTrue (conditional:bool) = System.Diagnostics.Debug.Assert(conditional)
type Error = {Code:int; Message:string}
[<EntryPoint>]
let main args =
let create (json: string) : Async<Result<string, Error>> =
let url = "http://api.example.com"
let request = WebRequest.CreateHttp(Uri url)
request.Method <- "GET"
async {
try
// http call
return Ok "result"
with :? WebException as e ->
return Error {Code = 500; Message = "Internal Server Error"}
}
let chain = create >> AsyncResult.bind (fun (result: string) -> (async {return Ok "more results"}))
match chain "initial data" |> Async.RunSynchronously with
| Ok data -> Assert.IsTrue(true)
| Error error -> Assert.IsTrue(false)
0

Parameterizing/Extracting Discriminated Union cases

Currently i'm working in a game and use Event/Observables much, one thing i run into was to eliminate some redundant code, and i didn't found a way to do it. To explain it, let's assume we have following DU and an Observable for this DU.
type Health =
| Healed
| Damaged
| Died
| Revived
let health = Event<Health>()
let pub = health.Publish
I have a lot of this kind of structures. Having all "Health" Messages grouped together is helpfull and needed in some situations, but in some situations i only care for a special Message. Because that is still often needed i use Observable.choose to separate those message. I have then code like this.
let healed = pub |> Observable.choose (function
| Healed -> Some ()
| _ -> None
)
let damaged = pub |> Observable.choose (function
| Damaged -> Some ()
| _ -> None
)
Writing this kind of code is actually pretty repetitive and annoying. I have a lot of those types and messages. So one "rule" of functional programming is "Parametrize all the things". So i wrote a function only to just help me.
let only msg pub = pub |> Observable.choose (function
| x when x = msg -> Some ()
| _ -> None
)
With such a function in place, now the code becomes a lot shorter and less annoying to write.
let healed = pub |> only Healed
let damaged = pub |> only Damaged
let died = pub |> only Died
let revived = pub |> only Revived
EDIT:
The important thing to note. healed, damaged, died, revived are now of type IObservable<unit> not IObservable<Health>. The idea is not just to separate the messages. This can be easily achieved with Observable.filter. The idea is that the the data for each case additional get extracted. For DU case that don't carry any additional data this is easy, as i only have to write Some () in the Observable.choose function.
But this only works, as long the different cases in a DU don't expect additional values. Unlucky i also have a lot of cases that carry additional information. For example instead of Healed or Damaged i have HealedBy of int. So a message also contains additional how much something got healed. What i'm doing is something like this, in this case.
let healedBy = pub |> Observable.choose (function
| HealedBy x -> Some x
| _ -> None
)
But what i really want is to write it something like this
let healedBy = pub |> onlyWith HealeadBy
What i'm expecting is to get an Observable<int>. And i didn't found any way how to do it. I cannot write a function like only above. because when i try to evaluate msg inside a Pattern Matching then it is just seen as a variable to Pattern Match all cases. I cannot say something like: "Match on the case inside the variable."
I can check if a variable is of some specific case. I can do if x = HealedBy then but after that, i cannot extract any kind of data from x. What i'm really need is something like an "unsecure" extracting like option for example provide it with optional.Value. Does there exists any way to implement such a "onlyWith" function to remove the boilerplate?
EDIT:
The idea is not just separating the different messages. This can be achieved through Observable.filter. Here healedBy is of type IObservable<int> NOT IObservable<Health> anymore. The big idea is to separate the messages AND extract the data it carries along AND doing it without much boilerplate. I already can separate and extract it in one go with Observable.choose currently. As long as a case don't have any additional data i can use the only function to get rid of the boilerplate.
But as soon a case has additional data i'm back at writing the repetitive Observable.Choose function and do all the Pattern Matching again. The thing is currently i have code like this.
let observ = pub |> Observable.choose (function
| X (a) -> Some a
| _ -> None
)
And i have this kind of stuff for a lot of messages and different types. But the only thing that changes is the "X" in it. So i obviously want to Parameterize "X" so i don't have to write the whole construct again and again. At best it just should be
let observ = anyObservable |> onlyWith CaseIWantToSeparate
But the new Observable is of the type of the specific case i separated. Not the type of the DU itself.
The behaviour it appears you are looking for doesn't exist, it works fine in your first example because you can always consistently return a unit option.
let only msg pub =
pub |> Observable.choose (function
| x when x = msg -> Some ()
| _ -> None)
Notice that this has type: 'a -> IObservable<'a> -> IObservable<unit>
Now, let's imagine for the sake of creating a clear example that I define some new DU that can contain several types:
type Example =
|String of string
|Int of int
|Float of float
Imagine, as a thought exercise, I now try to define some general function that does the same as the above. What might its type signature be?
Example -> IObservable<Example> -> IObservable<???>
??? can't be any of the concrete types above because the types are all different, nor can it be a generic type for the same reason.
Since it's impossible to come up with a sensible type signature for this function, that's a pretty strong implication that this isn't the way to do it.
The core of the problem you are experiencing is that you can't decide on a return type at runtime, returning a data type that can be of several different possible but defined cases is precisely the problem discriminated unions help you solve.
As such, your only option is to explicitly handle each case, you already know or have seen several options for how to do this. Personally, I don't see anything too horrible about defining some helper functions to use:
let tryGetHealedValue = function
|HealedBy hp -> Some hp
|None -> None
let tryGetDamagedValue = function
|DamagedBy dmg -> Some dmg
|None -> None
The usual route in these situations is to define predicates for cases, and then use them for filtering:
type Health = | Healed | Damaged | Died | Revived
let isHealed = function | Healed -> true | _ -> false
let isDamaged = function | Damaged -> true | _ -> false
let isDied = function | Died -> true | _ -> false
let isRevived = function | Revived -> true | _ -> false
let onlyHealed = pub |> Observable.filter isHealed
UPDATE
Based on your comment: if you want to not only filter messages, but also unwrap their data, you can define similar option-typed functions and use them with Observable.choose:
type Health = | HealedBy of int | DamagedBy of int | Died | Revived
let getHealed = function | HealedBy x -> Some x | _ -> None
let getDamaged = function | DamagedBy x -> Some x | _ -> None
let getDied = function | Died -> Some() | _ -> None
let getRevived = function | Revived -> Some() | _ -> None
let onlyHealed = pub |> Observable.choose getHealed // : Observable<int>
let onlyDamaged = pub |> Observable.choose getDamaged // : Observable<int>
let onlyDied = pub |> Observable.choose getDied // : Observable<unit>
You can use reflection to do this I think. This might be pretty slow:
open Microsoft.FSharp.Reflection
type Health =
| Healed of int
| Damaged of int
| Died
| Revived
let GetUnionCaseInfo (x:'a) =
match FSharpValue.GetUnionFields(x, typeof<'a>) with
| case, [||] -> (case.Name, null )
| case, value -> (case.Name, value.[0] )
let health = Event<Health>()
let pub = health.Publish
let only msg pub = pub |> Observable.choose (function
| x when x = msg -> Some(snd (GetUnionCaseInfo(x)))
| x when fst (GetUnionCaseInfo(x)) = fst (GetUnionCaseInfo(msg))
-> Some(snd (GetUnionCaseInfo(x)))
| _ -> None
)
let healed = pub |> only (Healed 0)
let damaged = pub |> only (Damaged 0)
let died = pub |> only Died
let revived = pub |> only Revived
[<EntryPoint>]
let main argv =
let healing = Healed 50
let damage = Damaged 100
let die = Died
let revive = Revived
healed.Add (fun i ->
printfn "We healed for %A." i)
damaged.Add (fun i ->
printfn "We took %A damage." i)
died.Add (fun i ->
printfn "We died.")
revived.Add (fun i ->
printfn "We revived.")
health.Trigger(damage)
//We took 100 damage.
health.Trigger(die)
//We died.
health.Trigger(healing)
//We healed for 50.
health.Trigger(revive)
//We revived.
0 // return an integer exit code
It doesn't feel like you can get your onlyWith function without making some significant changes elsewhere. You can't really generalize the function you pass in for the HealedBy case while staying within the type system (I suppose you could cheat with reflection).
One thing that seems like a good idea would be to introduce a wrapper for the Healed type instead of having a HealedBy type:
type QuantifiedHealth<'a> = { health: Health; amount: 'a }
and then you can have an onlyWith function like this:
let onlyWith msg pub =
pub |> Observable.choose (function
| { health = health; amount = amount } when health = msg -> Some amount
| _ -> None)
I guess you can even go one step further while you're at it, and parameterize your type by both the label and the amount types to make it truly generic:
type Quantified<'label,'amount> = { label: 'label; amount: 'amount }
Edit: To reitarate, you keep this DU:
type Health =
| Healed
| Damaged
| Died
| Revived
Then you make your health event - still a single one - use the Quantified type:
let health = Event<Quantified<Health, int>>()
let pub = health.Publish
You can trigger the event with messages like { label = Healed; amount = 10 } or { label = Died; amount = 0 }. And you can use the only and onlyWith functions to filter and project the event stream to IObservable<unit> and IObservable<int> respectively, without introducing any boilerplate filtering functions.
let healed : IObservable<int> = pub |> onlyWith Healed
let damaged : IObservable<int> = pub |> onlyWith Damaged
let died : IObservable<unit> = pub |> only Died
let revived : IObservable<unit> = pub |> only Revived
The label alone is enough to differentiate between records representing "Healed" and "Died" cases, you no longer need to walk around the payload you would have in your old "HealedBy" case. Also, if you now add a Mana or Stamina DU, you can reuse the same generic functions with Quantified<Mana, float> type etc.
Does this make sense to you?
Arguably it's slightly contrived compared to a simple DU with "HealedBy" and "DamagedBy", but it does optimize the use case that you care for.

Extending Core.Option module in F#

I want to extend one of the existing "core" modules, like 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 bind function, but I think filter method for options in some case is more convenient).
But unfortunetely I can't use filter method without explicitely open Microsoft.FSharp.Core namespace:
// 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 can't use functions from module without opening appropriate namespace.
F# compiler "opens" some predefine (core) namespace automatically (like Microsoft.FSharp.Core), this will not bring into the scope methods from "module extensions" and we still should open core namespaces manually.
My question is: Is there any workarounds?
Or the best way to extend "core" modules is to create such extensions in custom namespace and open this namespace manually?
// 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
For production code I would do what the Taha's answer suggests: create your own module and open/alias it as necessary. Most of your life as programmer will be spent reading code. It can be quite frustrating reading F# code where it is not clear where methods come from.
That being said, I was surprised to find that this works:
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)
It does not remove the need to write something in the head of your files, but it does work around needing to open a namespace. Not relevant for Microsoft.FSharp.Core as it is always open by default, but helpful for other namespaces.
In order to extend an 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
Does it help if you add the AutoOpen attribute to the module?
[<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
EDIT
This works, but only across assembly borders. It doesn't work within the same assembly:
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 ()
To call it from another assembly:
[<EntryPoint>]
let main args =
let f () = Some "" |> Option.filter (fun f -> true)
Console.WriteLine("Hello world!")
0
According to the docs something like this should work in extending a type. However I must have got something wrong as it won't compile and gives. the following error:
One or more of the declared type parameters for this type extension
have a missing or wrong type constraint not matching the original type
constraints on 'Option<_>'F# Compiler(957)
open System.Runtime.CompilerServices
[<Extension>]
type Option with
[<Extension>]
static member fromBool predicate word =
if predicate word
then Some word
else None
This isn't a functioning answer more an addendum to the original question. Not sure if it is worth opening a new thread?

Resources