Accessing a Specific Element in a Tuple

后端 未结 7 2172
南笙
南笙 2020-12-11 00:17

Haskell-newbie reporting in. Question is as follows: In Haskell, we have fst and snd that return the first and the second elements of a 2-tuple. Wh

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-11 00:48

    Why can't this be done easier? Or maybe there is some easy way?

    It can be easier using a recent alternative the lens package. The Tuple module has selectors for up to 9 element tuples and it is straight forward to define more if needed.

    > import Control.Lens
    > data A = A deriving (Show)
    > (1, '2', "3", A) ^. _1
    1
    > (1, '2', "3", A) ^. _2
    '2'
    > (1, '2', "3", A) ^. _3
    "3"
    > (1, '2', "3", A) ^. _4
    A
    

    You can also use the lens package to update elements polymorphically, change type on update.

    With and without infix operators:

    > (1, '2', "3", A) & _1 .~ "wow"
    ("wow",'2',"3",A)
     > set _1 "wow" (1, '2', "3", A)
    ("wow",'2',"3",A)
    

    The github readme is a good place to start to find out more about the underlying theory as well as numerous examples.


    Not just tuples

    Similar syntax works for Traverables and Foldables, so Trees, Maps, Vectors, etc. For example if I had a list of tuples I can access the third tuple element at the 1 index by composing the element 1 to access the first index element with _3 to access the third tuple element.

    [(1,2,3),(4,5,6),(7,8,9)] ^? element 1 . _3
    Just 6
    

提交回复
热议问题