Last active
December 21, 2015 00:49
-
-
Save tksk/6223397 to your computer and use it in GitHub Desktop.
Reading a collection of lists from file in scala
http://stackoverflow.com/questions/18187736/reading-a-collection-of-lists-from-file-in-scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 2 | |
1 1 | |
1 2 | |
4 3 | |
4 8 | |
1 5 | |
8 2 | |
8 2 | |
8 7 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Makelist { | |
val nums = """(\d+) (\d+)""".r | |
val tuples = io.Source.fromFile("list.txt").getLines collect { | |
case nums(label, num) => (label.toInt -> num.toInt) | |
} | |
def toList(tuples: Iterator[(Int, Int)]): Iterator[Seq[Int]] = { | |
if(!tuples.hasNext) Iterator.empty | |
else { | |
val (label, num) = tuples.next | |
val (succ, rest) = tuples.span(_._1 == label) | |
Iterator(num :: succ.map(_._2).toList) ++ toList(rest) | |
} | |
} | |
toList(tuples)foreach(println) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2,1,2 | |
3,8 | |
5 | |
2,2,7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment