Skip to content

Instantly share code, notes, and snippets.

@pschichtel
Last active November 1, 2015 00:41
Show Gist options
  • Save pschichtel/46bb678bfe1077a225e3 to your computer and use it in GitHub Desktop.
Save pschichtel/46bb678bfe1077a225e3 to your computer and use it in GitHub Desktop.
import scala.io.Source._
import java.lang.Character.{isWhitespace => isSpace}
import scala.annotation.tailrec
def parseLine(s: String): (String, Seq[String]) = {
parseCommand(s.iterator)
}
def parseCommand(s: Iterator[Char]): (String, Seq[String]) = {
val elements = parseElements(s)
(elements(0), elements.drop(1))
}
@tailrec
def parseElements(s: Iterator[Char], current: Seq[String] = Nil): Seq[String] = {
if (s.hasNext) parseElements(s, current :+ parseElement(s))
else current
}
@tailrec
def parseElement(s: Iterator[Char], current: String = "", quoted: Boolean = false): String = {
if (s.hasNext) {
s.next match {
case '"' if !quoted =>
parseElement(s, current, quoted = true)
case '"' if quoted =>
current
case c if isSpace(c) && current.isEmpty && !quoted =>
parseElement(s, current, quoted)
case c if isSpace(c) && !quoted =>
current
case c =>
parseElement(s, current + c, quoted)
}
} else current
}
def run(name: String, args: Seq[String]): Unit = {
println(s"$name '${args.mkString("' '")}'")
}
fromFile("input.txt")
.getLines()
.map(_.trim)
.filter(_.nonEmpty)
.map(parseLine)
.foreach((run _).tupled)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment