Is there a family of Haskell functions for sequencing tuples of applicatives?

128 Views Asked by At

Is there a standard function, or family of functions, for sequencing tuples of applicatives, as a generalization of sequenceA? Like the following, except for all reasonable tuple lengths:

sequence3TupleA :: Applicative f => (f a1, f a2, f a3) -> f (a1, a2, a3)

I believe this should be possible to implement (it is for the applicatives I'm working with anyway).

I found SequenceT from Data.Tuple.Sequence, but it appears to require a monad and also it doesn't seem to actually contain the sequence function (I am probably misreading the documentation somehow).

2

There are 2 best solutions below

1
Ari Fordsham On BEST ANSWER

The SequenceT typeclass and its method sequenceT from the tuple package does indeed do what you're looking for. Unfortunately, this package seems to have been abandoned since 2014, before the Applicative typeclass was introduced, so only works with Monad instances. An issue to sort this has been open since 2017, and an associated pull request was closed by the contributor.

As @lsmor mentions in a comment, this function is not difficult, its definition is:

sequence3TupleA (a, b, c) = (,,) <$> a <*> b <*> c
0
willeM_ Van Onsem On

Tuples are a bit a "pain" in Haskell, because the type is not recursive, producing functions requires to implement this for all tuples. There have been proposals that (a, b, c) for example is syntactical sugar for (a, (b, c)) and that only 2-tuples really exist, or at least from a type-system point-of-view. This is to some extend what a HList is doing.

The pattern that @Ismor described can however be implemented through template Haskell. I found the question quite fascinating, and implemented this for the tuple-append package: it defines a typeclass SequenceTuple that implements a sequenceTupleA and sequenceTupleA_ that implements these for tuples up to length 62, since this is the upperbound of GHC for the number of elements in a tuple, although very likely using such large tuples will never be necessary.