Abhishek Choudhary
Abhishek Choudhary

Reputation: 8395

How to destructure a tuple to multiple tuple in scala

I have a file containing a line

4 3 2
5 6 7
9 8 2

I am splitting the line by tab and then want to break the content into 2 pieces

What is the way to convert each line of input to 2 seperate tuple as following-

(4 3 2) = (4 1 2) & (3 1 2) 

Upvotes: 0

Views: 591

Answers (1)

slouc
slouc

Reputation: 9698

I am assuming that:

  • each tab-separated line consists of three elements
  • elements within each line are separated with exactly one space character
  • each line needs to be converted to a tuple of tuples

In case I got any of these wrong (e.g. there can be more than 3 elements in each row or you need different structures than tuples) it can be easily adapted.

val file = "4 3 2\t5 6 7\t9 8 2"

val lines = file.split("\t").map(line => line.split(" ").toList)

val newLines = lines.map({
  case a :: b :: c :: Nil => ((a, "1", c), (b, "1", c))
})

newLines.map(println)

//  ((4, 1, 2), (3, 1, 2))
//  ((5, 1, 7), (6, 1, 7))
//  ((9, 1, 2), (8, 1, 2))

EDIT:

This answer was based on the logic that you wrote initially in your question and which said that you want this kind of map: ((a b c) => (a 1 c) (b 1 c)). I can see now that you removed that part so I'm not sure if the logic in my solution is right, but now that you have the basic skeleton you can modify as you need.

Upvotes: 2

Related Questions