Ulrar
Ulrar

Reputation: 983

Convert a list of tuples to multiple lists

I'm looking for a way to parse some JSON into something usable. I'm getting what's basically a list of X-tuple, for example with three values :

[
  [1, 323, 985],
  [98, 21234, 46135]
]

Now I'd like to parse that JSON and convert it to a list of lists. I'm okay with the type being always the same, so I think Float or Double would be the ideal since it should allow to hold any numerical value. Something like [[Float]] would be perfect. In this example that would be :

[[1.0, 98.0], [323.0, 21234.0], [985.0, 46135.0]]

This would be easy enough if I knew how many values would be in the document, but I don't, I only know they'll be number (either Int or Float). Is there a way to iterate over the fields of a tuple like you'd map over a list ? I realise that's not what a tuple is supposed to be for, but I have no control over what generates the json, and I'd really like to avoid writing by hand functions for 2-tuples, 3-tuples, 4-tuples ..

Thanks

EDIT : Seems like I'm looking for a generic version of unzip, that would work on any size

Upvotes: 0

Views: 260

Answers (1)

castletheperson
castletheperson

Reputation: 33466

You can parse the JSON with the aeson package using decode, and then flip the rows and columns of the 2D list with transpose.

import Data.Aeson (decode)
import Data.String (fromString)
import Data.List (transpose)

parseFloats :: String -> Maybe [[Float]]
parseFloats = fmap transpose . decode . fromString

Upvotes: 3

Related Questions