Haskell List of tuples to list?

后端 未结 5 1610
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 13:27

Is it possible to convert a list of tuples [(Int,Int)] as a generic way which valid to any input size ? .. i saw in various questions thats its not possible gen

5条回答
  •  悲哀的现实
    2020-12-31 13:58

    The lens library handles this and similar cases consistently.

    > import Control.Lens
    > toListOf (traverse . both) [(1,2),(3,4)]
                ^          ^
                |          |> Traversal of the tuple (a, a)
                |> Traversal of a list [b]
    [1,2,3,4]
    

    To convert from a list of lists:

    > toListOf (traverse . traverse) [[1,2],[3,4],[5,6,7]]
    [1,2,3,4,5,6,7]
    

    addition edit:


    traverse works with Traversable

    traverse will work with any datatype that has a Traversable instance, for example trees.

    > import Data.Tree
    > let t = Node 1 [Node 2 [Node 3 [], Node 4 []], Node 5 []]
    > let prettyTree = drawTree . fmap show
    > prettyTree t
    1
    |
    +- 2
    |  |
    |  +- 3
    |  |
    |  `- 4
    |
    `- 5
    > toListOf (traverse . traverse) [t, t]
    [1,2,3,4,5,1,2,3,4,5]
    

提交回复
热议问题