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.
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.
Such type classes give only coding (syntax) convenience, I don't see how to build generalized over tuple type tools upon them. If you are looking for tuple generalization, check the discussion about heterogeneous vectors on Reddit.
Also note, that for ordinary structures it is preferable to define your own ADTs and provide getters with sensible names then use tuples of high arity.
Edit: however, as is7s pointed in the comment, there is a number of packages on hackage which provide indexing functions for tuples of arbitrary length.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With