Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple Unpacking in Map Operations

I frequently find myself working with Lists, Seqs, and Iterators of Tuples and would like to do something like the following,

val arrayOfTuples = List((1, "Two"), (3, "Four")) arrayOfTuples.map { (e1: Int, e2: String) => e1.toString + e2 } 

However, the compiler never seems to agree with this syntax. Instead, I end up writing,

arrayOfTuples.map {      t =>      val e1 = t._1     val e2 = t._2     e1.toString + e2  } 

Which is just silly. How can I get around this?

like image 760
duckworthd Avatar asked Aug 01 '11 22:08

duckworthd


People also ask

What is tuple unpacking?

Unpacking a tuple means splitting the tuple's elements into individual variables. For example: x, y = (1, 2) Code language: Python (python)

How does tuple unpacking work in Python?

Unpacking Tuples When we put tuples on both sides of an assignment operator, a tuple unpacking operation takes place. The values on the right are assigned to the variables on the left according to their relative position in each tuple . As you can see in the above example, a will be 1 , b will be 2 , and c will be 3 .

What is tuple packing and unpacking?

Tuple packing refers to assigning multiple values into a tuple. Tuple unpacking refers to assigning a tuple into multiple variables.

Is tuple a map?

Maps or hash tables are collections of key value pairs. Tuples are an immutable sequence of values and are used for aggregating values.


2 Answers

A work around is to use case :

arrayOfTuples map {case (e1: Int, e2: String) => e1.toString + e2} 
like image 67
Nicolas Avatar answered Nov 05 '22 16:11

Nicolas


I like the tupled function; it's both convenient and not least, type safe:

import Function.tupled arrayOfTuples map tupled { (e1, e2) => e1.toString + e2 } 
like image 45
thoredge Avatar answered Nov 05 '22 16:11

thoredge