How to collapse a match on a discriminatory union in F #

How to take the results of a function that returns an object and pass it to a discriminatory union in F #?

Problem scenario, I am working with javascript executor on webdriver in selenium. The docs indicate that the output should be an object of type certian or type list. (Ref https://www.w3.org/TR/webdriver/#executing-script )

I would like to give the returning object some structure, translating it into a discriminated union, so that later it can be compared.

Casting does not work directly, and it is not allowed to create constructors for union types, so I cannot drop them exactly. What is the correct way to do this?

type JsResult = 
    | E of IWebElement
    | I of Int64
    | B of bool
    | S of String
    | LE of IWebElement list
    | LI of Int64 list
    | LB of bool list
    | LS of String list
    | N of Object
    override self.ToString () =
        match self with 
        | E e -> e.Text
        | I i -> i.ToString()
        | B b -> b.ToString() 
        | S s -> s
        | LE le -> String.concat " " (le |> Seq.map(fun x-> x.Text))
        | LI li -> String.concat " " (li |> Seq.map(fun x-> x.ToString()))
        | LB lb -> String.concat " " (lb |> Seq.map(fun x-> x.ToString()))
        | LS ls -> String.concat " " ls
        | N _ -> String.Empty

let execute script : JsResult = (browser :?> IJavaScriptExecutor).ExecuteScript(script) :> JsResult
+4
source share
1

, factory? :

type JsResult = 

    // ...

    with static member ofObject o =
        match box o with
        | :? IWebElement as e -> E e
        | :? Int64 as i -> I i
        | :? bool as b -> B b
        | :? String as s -> S s
        | :? (IWebElement list) as le -> LE le
        | :? (Int64 list) as li -> LI li
        | :? (bool list) as lb -> LB lb
        | :? (String list) as ls -> LS ls
        | :? Object as n -> N o
        | _ -> failwith "No wrapper available for type"


let execute script : JsResult = (browser :?> IJavaScriptExecutor).ExecuteScript(script) |> JsResult.ofObject

( , , int, bool).

+6

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


All Articles