Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten a nested tuple?

Tags:

I have a nested tuple structure like (String,(String,Double)) and I want to transform it to (String,String,Double). I have various kinds of nested tuple, and I don't want to transform each manually. Is there any convenient way to do that?

like image 337
zjffdu Avatar asked Dec 04 '12 08:12

zjffdu


People also ask

How do you flatten a tuple?

Flattening a tuple of list is converting the tuple of lists to a simple tuple containing all individual elements of the lists of the tuple. To flatten a tuple of list to a tuple we need to put all the elements of the list in a main tuple container.

How do you unpack a tuple?

Python uses a special syntax to pass optional arguments (*args) for tuple unpacking. This means that there can be many number of arguments in place of (*args) in python. All values will be assigned to every variable on the left-hand side and all remaining values will be assigned to *args .

How do you nest a tuple?

When it is required to concatenate tuples to nested tuples, the '+' operator can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error.

Is nested tuple possible?

Tuples can be nested Tuples can contain other compound objects, including lists, dictionaries, and other tuples. Hence, tuples can be nested inside of other tuples.


2 Answers

If you use shapeless, this is exactly what you need, I think.

like image 156
xiefei Avatar answered Oct 02 '22 01:10

xiefei


There is no flatten on a Tupple. But if you know the structure, you can do something like this:

implicit def flatten1[A, B, C](t: ((A, B), C)): (A, B, C) = (t._1._1, t._1._2, t._2) implicit def flatten2[A, B, C](t: (A, (B, C))): (A, B, C) = (t._1, t._2._1, t._2._2) 

This will flatten Tupple with any types. You can also add the implicit keyword to the definition. This works only for three elements. You can flatten Tupple like:

(1, ("hello", 42.0))   => (1, "hello", 42.0) (("test", 3.7f), "hi") => ("test", 3.7f, "hi") 

Multiple nested Tupple cannot be flatten to the ground, because there are only three elements in the return type:

((1, (2, 3)),4)        => (1, (2, 3), 4) 
like image 37
tgr Avatar answered Oct 02 '22 01:10

tgr