Scala split a string into a tuple

I would like to split a string into a space that has 4 elements:

1 1 4.57 0.83 

and I'm trying to convert to List [(String, String, Point)], so the first two partitions are the first two elements in the list, and the last two are Point. I am doing the following, but it does not work:

 Source.fromFile(filename).getLines.map(string => { val split = string.split(" ") (split(0), split(1), split(2)) }).map{t => List(t._1, t._2, t._3)}.toIterator 
+7
source share
5 answers

You can use pattern matching to extract what you need from the array:

  case class Point(pts: Seq[Double]) val lines = List("1 1 4.34 2.34") val coords = lines.collect(_.split("\\s+") match { case Array(s1, s2, points @ _*) => (s1, s2, Point(points.map(_.toDouble))) }) 
+8
source

How about this:

 scala> case class Point(x: Double, y: Double) defined class Point scala> s43.split("\\s+") match { case Array(i, j, x, y) => (i.toInt, j.toInt, Point(x.toDouble, y.toDouble)) } res00: (Int, Int, Point) = (1,1,Point(4.57,0.83)) 
+13
source

You do not convert the third and fourth tokens to Point , and you do not convert strings to List . In addition, you do not treat each element as Tuple3 , but as List .

The following should be more in line with what you are looking for.

 case class Point(x: Double, y: Double) // Simple point class Source.fromFile(filename).getLines.map(line => { val tokens = line.split("""\s+""") // Use a regex to avoid empty tokens (tokens(0), tokens(1), Point(tokens(2).toDouble, tokens(3).toDouble)) }).toList // Convert from an Iterator to List 
+1
source
 case class Point(pts: Seq[Double]) val lines = "1 1 4.34 2.34" val splitLines = lines.split("\\s+") match { case Array(s1, s2, points @ _*) => (s1, s2, Point(points.map(_.toDouble))) } 

And for the curious, matching @in pattern binds a variable to a pattern, so points @ _* binds variables to a pattern * _ AND * _ matches the rest of the array, so the dots end up with Seq [String].

+1
source

There are ways to convert a tuple to a list or Seq, one way is

 scala> (1,2,3).productIterator.toList res12: List[Any] = List(1, 2, 3) 

But as you can see, the return type is Any and NOT INTEGER

To convert to different types, you use the Hlist of https://github.com/milessabin/shapeless

-one
source

All Articles