Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Last active August 29, 2015 14:05
Show Gist options
  • Save sungkmi/b348b427522eedbe88d9 to your computer and use it in GitHub Desktop.
Save sungkmi/b348b427522eedbe88d9 to your computer and use it in GitHub Desktop.
object IgnoreAllMyComments extends App {
trait State
case class Closed(last: Option[Char]) extends State
case class Open(n: Int, last: Option[Char]) extends State
def ignoreComments(in: Iterator[Char])(out: Char => Unit): Unit = {
def step(s: State, ch: Char): State = (s, ch) match {
case (Closed(Some('/')),'*') => Open(1, None)
case (Closed(last), ch) =>
if (last.nonEmpty) out(last.get)
Closed(Some(ch))
case (Open(n, Some('/')), '*') => Open(n+1, Some(ch))
case (Open(1, Some('*')), '/') => Closed(None)
case (Open(n, Some('*')), '/') => Open(n-1, None)
case (Open(n, last), ch) => Open(n, Some(ch))
}
(Closed(None) /:[State] in) (step) match {
case Closed(Some(ch)) => out(ch)
case _ =>
}
}
def process(in: Iterator[Char])(charOut: Char => Unit) = {
ignoreComments(in)(charOut)
}
val writer = new java.io.PrintWriter("e.small.out")
try {
writer.println("Case #1:")
process(io.Source.fromFile("E-small-practice.in").iter)(writer.print)
} finally {
writer.flush(); writer.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment