omar
omar

Reputation: 411

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:

[["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'

Upvotes: 0

Views: 708

Answers (3)

evzh
evzh

Reputation: 323

If you are sure that your tuple is of type (String, Int, Int) then you just write

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

and map it over what you have, [(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)

  • Switching the show objects, like (String, a, b) mixing (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.

Upvotes: 0

erisco
erisco

Reputation: 14329

In addition to @chi's answer, you may also try a sum of Int and String, called 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.

Upvotes: 0

chi
chi

Reputation: 116174

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. That list can not have type [String], nor type [Int], for instance.

Upvotes: 2

Related Questions