gcanti / fp-ts

Functional programming in TypeScript
https://gcanti.github.io/fp-ts/
MIT License
10.74k stars 503 forks source link

What is the inverse operation of A.sequenceT? #1860

Open Carsten-Leue opened 1 year ago

Carsten-Leue commented 1 year ago

The operation A.sequenceT allows to convert a sequence of typed Monads into a Monad of a typed tuple, such as in this Option example:

        const sequenceO = A.sequenceT(O.Apply);

        const o1: Option<number> = O.some(1);
        const o2: Option<string> = O.some("1");

        const o12: Option<[number, string]> = sequenceO(o1, o2);

what is the best representation of the inverse operation?

The best I could do as a special case for Option was:

        const unsequenceO = O.fold<[number, string], [Option<number>, Option<string>]>(() => [O.none, O.none], ([s1, s2]) => [O.some(s1), O.some(s2)]);

        const [u1, u2] = unsequenceO(o12);

but I wonder if there exists a concept (and more generic implementation) for this.

ENvironmentSet commented 1 year ago

It’s not possible for arbitrary monad to have inverse function of ‘sequence’ since there is no deterministic(or even possible) way to decompose given monadic value with single effect into monadic value with serveral, chained effects. Just as it’s not possible to know what values were used to calculate given value that forms monoid. (1 + 9 is 10, but 2 + 8 and 3 + 7 is also 10, it’s not possible to naturally determine combination to be used as result of inverse function)

PS. Even for Option monad, it’s still not possible to implement inverse function of sequence.

sequenceO(none, some(1)) is none, but sequenceO(none, none) is none too.