Use of function within discriminatory association

I would like to do some unit tests for a function that takes a DU and returns another:

type Commands = 
  | Schedule of string
  | Abandon of string

type Events =
  | Scheduled of string
  | Abandonned of string

The function is as follows:

let exec state = function
    | Schedule (cmd) -> Choice1Of2( Scheduled("yes")) 
    | Abandon(cmd)  -> Choice1Of2( Abandonned ("no")) 

My tests are as follows:

let result:Choice<Events,string> = exec "initial state" <| Schedule("myCommand");;
Result

has the following type Choice<Events,string>, I would like to get some quick function to use them as follows:

assertEvent Scheduled (fun e -> Assert.Equal("should produce GameScheduled Event",gameScheduled, e)) result

But for this I will have the following home function assert:

let assertEvent<'TEvent> f g result =
    match result  with
        | Choice1Of2(e) -> 
            match e with 
            | f(evt) ->  g(evt)
            | _ -> Assert.None("event not recognised",Some(e)) 
        | Choice2Of2(reason) -> Assert.None("reason",Some(reason))

I expected the f function to allow pattern matching on the fly, but that is not the case. Instead, I have the following error:

The pattern disciminator 'f' is not defined

Am I doing something wrong? my fsharp skills are not so high ...

+4
source share
1 answer

f , :

let assertEvent<'TEvent> (|F|_|) g result =
    match result  with
        | Choice1Of2(e) -> 
            match e with 
            | F(evt) ->  g(evt)
            | _ -> Assert.None("event not recognised",Some(e)) 
        | Choice2Of2(reason) -> Assert.None("reason",Some(reason))

, , , , :

assertEvent
    (function Scheduled(x) -> Some x | _ -> None)
    (fun e -> Assert.Equal("should produce GameScheduled Event",gameScheduled, e))
    result

. , , .

, Choice<'a, 'b>:

let toOption1 = function Choice1Of2 x -> Some x | _ -> None

Choice<'a,'b> -> 'a option. ( toOption2.)

, , , :

result
|> toOption1
|> Option.map (function Scheduled x -> x | _ -> "")
|> Option.exists ((=) expected)

, Unquote, . , .

+4

Source: https://habr.com/ru/post/1610430/


All Articles