Operator overload for discriminated association

I am trying to write some numerical code that can work with both scalars and vectors (in this case, these are D and DV types, respectively, from DiffSharp). Sometimes I want to be able to use either so that I have defined a discriminatory union for them:

type IBroadcastable =
    | Scalar of D
    | Vect of DV

Many operators are already overloaded for both of these types, so for their use in IBroadcastableI am writing to add code like this to the union:

static member Exp x = 
    match x with
        | Scalar x -> Scalar (exp x)
        | Vect x -> Vect (exp x)

It seems very redundant. Is there any way to use the operator in a union without having to write a new overload for it? Or should I use a different scheme (i.e. non-discriminatory union)? An example of what I want to use for this type:

let ll (y: IBroadcastable) (theta: IBroadcastable) = y*theta-(exp theta)

* - ( ), , exp , . , y, DiffSharp theta.

+4
3

, , . , , .

, F # . function, , : x , . , , :

type DU =
| A of float * float
| B of float * string
with
    static member Exp = function
        | A (b, _)
        | B (b, _) -> exp b // only write the logic once
+2

ll - ​​ , , , D DV. inline, :

let inline ll y theta = y*theta-(exp theta)

inline F # , ( , .NET).

, , , D DV, F #, exp. , , .

, D DV Foo, string, :

let inline foo (x:^T) = 
  (^T : (member Foo : string) x)

let inline ll y theta = y*theta-(exp theta)+foo y
+1

, - :

type IBroadcastable =
| Scalar of D
| Vect of DV

let inline private lift s v = function
| Scalar d -> Scalar (s d)
| Vect dv -> Vect (v dv)

type IBroadcastable with
    static member Exp b = lift exp exp b
    static member Cos b = lift cos cos b
    ...

and if you want to support binary operators, you can define the appropriate one lift2- but carefully consider whether the first argument of the binary operator makes sense Scalarand the second - a Vect(or vice versa) - if not, then your discriminatory union cannot be a suitable abstraction .

+1
source

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


All Articles