Haskell List of tuples to list?

后端 未结 5 1467
爱一瞬间的悲伤
爱一瞬间的悲伤 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:45

    Your question is not very certain about how the tuples should be converted into a list. I assume that you want to have them flattend - for instance, [(1,2),(3,4)] should become [1,2,3,4].

    This translation is only possible, if the two elements of your tuple are of the same type. In this case you can do something like this:

    tupleToList :: [(a,a)] -> [a]
    tupleToList ((a,b):xs) = a : b : tupleToList xs
    tupleToList _          = []
    

    In the general case, such a translation is impossible. One thing I could imagine to make the impossible possible is to use Either to wrap up the two different types:

    tupleToList :: [(a,b)] -> [Either a b]
    tupleToList ((a,b):xs) = Left a : Right b : tupleToList xs
    

提交回复
热议问题