Hi - I am struggling a little bit with Unions in C...
# general
t
Hi - I am struggling a little bit with Unions in C#. Specifically I want to map an InputUnion<T0, T1> to a different InputUnion<U0, U1>. I can use an apply, and I can get an Output<Union<U0, U1>> but I'm really struggling to find a nice way to do this. The only solution so far is to use a Match within an Apply to set the InputUnion<U0, U1> to a specific value - ideally I would like to return an Output<Union<U0, U1>> and assign it to a property of type InputUnion<U0, U1>, but that's not possible. Furthermore the Map operation only allows me to map one or the other input (i.e. to InputUnion<T0, U1> or InputUnion<U0, T1>) but not both. Any ideas how I can get around this?
e
I think this type is missing the very obvious Bimap method. Which would let you write something like:
Copy code
input.Apply(union => union.Bimap(t0 => (U0)t0, t1 => (U1)t1));
As that doesn't exist yet you can use TryPick to get long hand version:
Copy code
input.Apply(union => {
    if (union.TryPickT0(out var t0, out var t1)) {
        return Union<U0, U1>.FromT0((U0)t0);
    } else {
        return Union<U0, U1>.FromT0((U1)t1);
    }
});
Actually I guess Match can do this as well:
Copy code
input.Apply(union => union.Match<Union<TResult0, TResult1>>(t0 => mapFunc0(t0), t1 => mapFunc1(t1)))
But a bimap function would be shorter and save those type annotations probably. Wonder if we should lift some of these methods to be directly on InputUnion as well
t
Thanks Fraser - yeah I got the Match which is nice, but the Apply returns an Ouput<Union<U0, U1>> but I can't figure out how to assign that to an InputUnion<U0, U1>
Bimap would be nice too though
e
Oh huh yeh InputUnion is missing some constructors/converters as well 😞 That's very dumb I'll get it fixed.
🙌 1
t
Amazing, thank you.