Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala split string to tuple

I would like to split a string on whitespace that has 4 elements:

1 1 4.57 0.83

and I am trying to convert into List[(String,String,Point)] such that first two splits are first two elements in the list and the last two is Point. I am doing the following but it doesn't seem to 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
like image 904
princess of persia Avatar asked Feb 20 '13 03:02

princess of persia


2 Answers

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))
like image 154
Randall Schulz Avatar answered Sep 21 '22 09:09

Randall Schulz


You could 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)))
    })
like image 35
Denis Tulskiy Avatar answered Sep 18 '22 09:09

Denis Tulskiy