Operator overloading for discriminated union

Viewed 420

I'm trying to write some numerical code that can work with either scalars or vectors (in this case it's the D and DV types respectively, from DiffSharp). Sometimes I want to be able to use either so I've defined a discriminated union for them:

type IBroadcastable =
    | Scalar of D
    | Vect of DV

A lot of operators are already overloaded for both of these types, so to use them on IBroadcastable I write add code like this to the union:

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

This seems very redundant. Is there any way I can use the operator on the union without having to write a new overload for it? Or I should I be using a different pattern (i.e. not a discriminated union)? An example of what I want to use this type for:

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

The * and - will have more complicated behaviour (array broadcasting), which it makes sense to have to describe myself, but the exp operator is simple, as above. This needs to be a function since I want to be able to partially apply the y argument, get the gradient with DiffSharp, and maximise it with respect to the theta argument.

3 Answers
Related