How to declare a universal function that returns a type that satisfies several restrictions in F #?

What am I trying to write:

type A() =
    interface IX with ...
    interface IY with ...

type B() =
    interface IX with ...
    interface IY with ...

let mk t : 'T when 'T :> IX and 'T :> IY =
    match t with
    | Choice1 -> new A()
    | Choice2 -> new B()

Note the mk return type restrictions. However, it does not compile, the compiler complains that it cannot convert A and B to "T".

+3
source share
2 answers

Limiting the right, but the problem is that there is no type satisfying this limitation, and it will be as a supertype A, and so B.

match , upcast (:>) , . IX, IY, .

, .NET - IX+IY, , . , :

let (a:IX+IY) = new A()  // This isn't supported

, IX * IY, , . , , :

// Type: 'a -> IX * IY when 'a :> IX and 'a :> IY
let asTuple a = (a :> IX, a :> IY)

let mk t = 
  match t with 
  | Choice1Of2() -> new A() |> asTuple
  | Choice2Of2() -> new B() |> asTuple
+7

A B,

type IXY =
  inherit IX
  inherit IY

A B inherit IXY, mk IXY, ( , ).

+7

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


All Articles