Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 281
Landei Avatar asked Mar 12 '13 09:03

Landei


2 Answers

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.

like image 170
bgamari Avatar answered Sep 28 '22 16:09

bgamari


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.

like image 34
leventov Avatar answered Sep 28 '22 15:09

leventov