Frage

I have a problem where I need to make a tuplet of three elements. Let's suppose that I have a list, and I managed to write tuplet of two elements:

val list = (1 to 10).toList

val map1 = list.foldLeft(Map.empty[Int,String])( (map, value) => map + (value -> value.toString) )

Map(5 -> 5, 10 -> 10, 1 -> 1, 6 -> 6, 9 -> 9, 2 -> 2, 7 -> 7, 3 -> 3, 8 -> 8, 4 -> 4)

I want to make a tuplet of three elements. How can I do that?

I tried this code:

val map1 = list.foldLeft(Map.empty[Int,String])( (map, value, s) => map + (value -> value.toString -> value.toString) )

Map(5 -> 5 -> 5, 10 -> 10-> 10, 1 -> 1-> 1, 6 -> 6-> 6, 9 -> 9-> 9, 2 -> 2-> 2, 7 -> 7-> 7, 3 -> 3-> 3, 8 -> 8-> 8, 4 -> 4-> 4)

Keine korrekte Lösung

Andere Tipps

-> is just a sugar notation for a pair (a tuple of two items). The universal notation for tuples of any arity is a comma-delimited list in braces. E.g. (1,2,3) is a tuple of three integers, while as in your example the expression 1 -> 2 -> 3 would desugar to ((1,2),3), which is a tuple of a tuple of two ints and an int.

What you're trying to achieve with your code simply doesn't make any sense. A Map can be constructed from a list of pairs, treating the first element of the tuple as a key and the second as a value. Tuples of any other arities are not supported and wouldn't make sense in that case. You can however construct collections of other types (e.g., a List) containing tuples of any arities.

In general to convert a range into a Tuple3 you could do something like this:

(0 to 10) map (x=>(x,x*2,x+10))
res0: scala.collection.immutable.IndexedSeq[(Int, Int, Int)] = Vector((0,0,10), (1,2,11), (2,4,12), (3,6,13), (4,8,14), (5,10,15), (6,12,16), (7,14,17), (8,16,18), (9,18,19), (10,20,20))

To join 2 Seqs as a Tuple2 you zip them:

 (1 to 5) zip (10 to 15)
res3: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,10), (2,11), (3,12), (4,13), (5,14))

scala has built in support for zipping up to arity 3:

((0 to 3),(4 to 6),(7 to 9)).zipped.toList
res6: List[(Int, Int, Int)] = List((0,4,7), (1,5,8), (2,6,9))

If you need to do something similar to higher arities there's product-collections:

(0 to 3) flatZip (4 to 6) flatZip (7 to 9) flatZip (10 to 12)
res7: org.catch22.collections.immutable.CollSeq4[Int,Int,Int,Int] = 
CollSeq((0,4,7,10),
        (1,5,8,11),
        (2,6,9,12))

And finally there's shapeless which does lots of cool things but has a moderate learning curve.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top