4 ms·
> you can define _1 and _2 as lenses for accessing the first and second element respectively of a tuple: _1 :: Lens' (a,b) a _2 :: Lens' (a,b) b From
by gugagore 6y ago
> you can define _1 and _2 as lenses for accessing the first and second element respectively of a tuple:
_1 :: Lens' (a,b) a
_2 :: Lens' (a,b) b
From the looks of it, this is to access the first and second element specifically of a 2-tuple. I suppose if you had to generalize it, you would actually get a traversal or a prism or something, because those elements might not exist.
- bradrn 6y ago> From the looks of it, this is to access the first and second element specifically of a 2-tuple. Yes, this is correct. (I don’t know about other languages, but it’s worth noting that in Haskell, tuples are of fixed size — 2-tuples, 3-tuples etc. are considered completely different types. A result of this is that ‘tuple of any length’ is not a valid concept in Haskell; you have to write a separate definition for each tuple size.) > I suppose if you had to generalize it, you would actually get a traversal or a prism or something, because those elements might not exist. Well, it depends how you generalise it. Haskell lens libraries, for instance, use a more general type which allows _1 and _2 to work with 2-tuples and larger, _3 to work with 3-tuples and larger, _4 to work with 4-tuples and larger, and so on. Thus these remain lenses, as they always access exactly one value. Another generalisation is to define a lens allowing access of an arbitrary element of a list. This may not return a value, and thus is indeed a traversal.