0

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.

Carsten
  • 468
  • 4
  • 16
  • 1
    No, it is impossible to reverse the function application - from `sequenceO(O.some(1), O.none)` you cannot get back to `O.some(1)` – Bergi May 04 '23 at 10:24
  • Or are you looking for just `x => [x.map(fst), x.map(snd)]`? – Bergi May 04 '23 at 10:25
  • Hi @bergi - from `sequenceO(O.some(1), O.none)` I would come to `O.none` and would like to go back to `[O.none, O.none]` - indeed for the case of a pair this is a more elegant solution, maybe along these lines `const unsequenceO = (data: Option<[F, S]>) => [O.map(fst)(data), O.map(snd)(data)];` – Carsten May 04 '23 at 15:53
  • `map` in particular has the benefit that it works for any `Apply` functor, i.e. `unsequence = F => x => [F.map(fst)(x), F.map(snd)(x)]`, `unsequenceO = unsequence(Option)` – Bergi May 04 '23 at 16:55
  • I realize that the generalization of the approach to any functor would not behave as I expect. It works well for `Option` but if `F` were an `IO` monad, then the `map` approach would trigger the `IO` monad for the tuple for each invocation, potentially getting a different result each time. The `fold` approach would only trigger the tuple `IO` monad once and then extract each element. – Carsten May 05 '23 at 07:02
  • This cannot be generalized. As you have stated, there is a defined behavior for Option. However, in the case of IO, it would not be possible to undo the composition of functions. – Dennis Yang Jun 02 '23 at 18:30

0 Answers0