Why are there no "general" accessor functions for tuples in Haskell?

haskell, typeclass

Solution

One thing to note is that `fst` and `snd` only allow one to view into a 2-tuple. Generalizing them to other arities and operations quickly becomes painful. If you want to also, for instance, map on the first element of a tuple, you have to introduce another combinator (which, for the record, exists for 2-tuples as `Control.Arrow.first`). This quickly leads to an explosion in the number of combinators for high arity tuples.

That being said, `lens` provides some nice tools to working with tuples. `Control.Lens.Tuple` provides several index lenses `_1`, `_2`, etc. which allow access to the first, second, etc. elements of tuples up to arity 9.

For example,

>>> import Control.Lens
>>> let t = (1,2,3,5,6,7,2)
>>> t ^._1
1
>>> t & _1 .~ 'a'
('a',2,3,5,6,7,2)
>>> t & _1 +~ 41
(42,2,3,5,6,7,2)
>>> over _1 (+1) t
(2,2,3,5,6,7,2)

You may also be interested in the tuple instances in `Control.Lens.At`. Also, the `tuple-lenses` package provides some more general lenses for examining multiple tuple entries at once.

Problem

I know there is `fst` and `snd`, but why is there no "general" definition for such accessor functions using type classes? I would suggest something like ``` class Get1 p a | p -> a where get1 :: p -> a instance Get1 (a,b) a where get1 (x,_) = x instance Get1 (a,b,c) a where get1 (x,_,_) = x class Get2 p a | p -> a where get2 :: p -> a instance Get2 (a,b) b where get2 (_,x) = x instance Get2 (a,b,c) b where get2 (_,x,_) = x ``` Sure, you need some language extensions for this, but isn't this much more convenient like that? Especially you can add instances for your own types.

Original source