Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Vector[Vector[Char]] from a file

Tags:

scala

I'm a newbie, trying to read a file and create a Vector[Vector[Char]]. Each line of the file should result in a different vector.

Here's what I've come up with:

val empty: Vector[Vector[Char]]       = Vector()
lazy val lines: List[String]          = Source.fromFile("test.txt").getLines.toList
lazy val vecList: List[Vector[Char]]  = lines.map(str => Vector(str: _*))
lazy val vector: Vector[Vector[Char]] = vecList.foldRight(empty) (_ +: _)

The file will never be large, so scalability isn't an issue. The above code seems to work, but I feel like it's going all around the barn. Is there a simpler, more direct way to do this?

like image 423
saulspatz Avatar asked Jul 05 '26 10:07

saulspatz


1 Answers

The following is a solution using Scala 2.10:

source.getLines.to[Vector].map(_.to[Vector])
like image 148
Arjan Avatar answered Jul 06 '26 23:07

Arjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!