简体   繁体   English

Haskell:将元组列表转换为列表列表

[英]Haskell: converting a list of tuples into a list of lists

I have a list of tuples: 我有一个元组列表:

  [("book", 1,0), ("book", 2,0), ("title", 2,1)]

that I wanted to convert into a list of lists with the ints converted to Strings as well: 我想将int也转换为String的列表的列表:

[["book, "1","0"], ["book , "2", "0"]...]

I tried: 我试过了:

map(\(a, b, c) -> [a, b, c])myList

but I get the following error message: 但我收到以下错误消息:

* No instance for (Num [Char]) arising from a use of `myList'

You can not perform that conversion. 您无法执行该转换。 Lists, unlike tuples are homogeneous: they contain values of the same type, only. 与元组不同,列表是同质的:它们仅包含相同类型的值。

There's no such a list as ["book",1,0] , since it contains both strings and numbers. 没有["book",1,0]["book",1,0]这样的列表,因为它同时包含字符串和数字。 That list can not have type [String] , nor type [Int] , for instance. 例如,该列表不能具有[String]类型,也不能具有[Int]类型。

In addition to @chi's answer, you may also try a sum of Int and String , called Either Int String . 除了@chi的答案外,您还可以尝试将IntString求和,称为Either Int String

concatMap
  (\(s, x, y) -> [Right s, Left x, Left y])
  [("book", 1, 0), ("book", 2, 0), ("title", 2, 1)]
= [Right "book", Left 1, Left 0, Right "book",
  Left 2, Left 0, Right "title", Left 2, Left 1]

If the numbers are to be associated with the string, however, the list of tuples is a superior structure. 但是,如果数字与字符串相关联,则元组列表是高级结构。

If you are sure that your tuple is of type (String, Int, Int) then you just write 如果您确定您的元组的类型(String, Int, Int)则只需编写

tupleToList :: (String, Int, Int) -> [String]
tupleToList (a,b,c) = [a, show b, show c]

and map it over what you have, [(String, Int, Int)] . 并将其映射到您拥有的[(String, Int, Int)]

More generally, 更普遍,

tupleToList :: (Show a, Show b) => (String, a, b) -> [String]
tupleToList (a,b,c) = [a, show b, show c]

which allows you to insert any displayable thing in 2nd and 3rd place of the input tuple, but not being more general : for example, you can not have 这样您就可以在输入元组的第二和第三位置插入任何可显示的内容,但不能太笼统 :例如,您不能

  • Unfixed length of tuple, like (a,b,c) mixing with (a,b,c,d) 不固定的元组长度,例如(a,b,c)(a,b,c,d)

  • Switching the show objects, like (String, a, b) mixing (b, String, a) 切换show对象,例如(String, a, b)混合(b, String, a)

-- I mean, how would you store the different tuples in a list in the first place? -我的意思是,首先如何将不同的元组存储在列表中?

In case of that you really want, there is something called Heterogenous list which is never recommended and you cannot really get much out of it. 如果确实需要,则不建议使用称为异类列表的东西,您也无法真正从中获得很多收益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM