Haskell要列出的元组列表? [英] Haskell List of tuples to list?
问题描述
是否可以将元组列表 [(Int,Int)]
转换为对任何输入大小有效的通用方法? ..我在各种问题中看到这是不可能的一般性的例子:
pre $ type X = [(Int,Int)]
func :: X - > [Int]
元组应该被转换成列表。我假设你想让它们平展 - 例如, [(1,2),(3,4)]
应该变成 [1, 2,3,4]
。
如果元组的两个元素的类型相同,可以做这样的事情:
tupleToList :: [(a,a)] - > [a]
tupleToList((a,b):xs)= a:b:tupleToList xs
tupleToList _ = []
在一般情况下,这种翻译是不可能的。我可以想象的一件事是使用或者
来包装这两种不同的类型:
tupleToList :: [(a,b)] - > [a b]
tupleToList((a,b):xs)=左a:右b:tupleToList xs
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 generically
example :
type X = [(Int,Int)]
func :: X -> [Int]
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, than 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
这篇关于Haskell要列出的元组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!